#!/usr/bin/perl

use strict;
use warnings;
use File::Remove 'remove';

my $dir = shift @ARGV;
die "No directory" unless defined $dir && -d $dir;

my @history;

open H, "$dir/000Admin/history.txt" or die "cannot open: $!";
while(<H>) {
	push @history, $_;
}
close H;

while(@history > 2) {
	my $hist = shift @history;

	# 0000000001,add,file,07/20/2019,02:10:12,"qgis-dev","3.9.0-22","",
	my ($no, $op, $type, $date, $time, $pkg, $ver, $comment) = $hist =~ /^(\d+),([^,]+),([^,]+),([^,]+),([^,]+),"([^"]*)","([^"]*)","([^"]*)",\s*$/;

	print "# Remove $dir $no $pkg $ver\n";

	warn "File $dir/000Admin/$no not found" unless -f "$dir/000Admin/$no";
	next unless -f "$dir/000Admin/$no";

	open L, "$dir/000Admin/$no";
	while(<L>) {
		# "_3d.pdb\3DFA6386A14E42B4A0CAD8AC2B5B62B517","/tmp/tmp.N7zrpysFFK/apps/qgis-dev/pdb/_3d.pdb
		my ($file, $src) = /^"([^"]+)","(.*)\s*$/;
		$file =~ s#\\#/#g;

		warn "Directory $dir/$file not found" unless -d "$dir/$file";
		next unless -d "$dir/$file";

		remove(\1, {glob => 0}, "$dir/$file");
	}

	unlink("$dir/000Admin/$no");
}

open H, ">$dir/000Admin/history.txt" or die "cannot open: $!";
print H foreach @history;
close H;
