#!/bin/perl

# This program searches the KnotDB database for knot types, then checks that their mugshots
# exist and correspond to the current correct filename.

use strict;
use warnings;
use File::Slurp;
use File::Path;
use Data::Dumper;

# We start by loading the database.

my $DBFILE = read_file('KnotDB.pl');
my %knots;
eval($DBFILE);

my $mugname;
my %wknots = %knots;

my $numkeys = keys ( %wknots );
print "We have $numkeys entries in the original database. Checking mugshots...\n";
chdir "./mugshots" or die("Couldn't get to ./mugshots:$_\n");

my $key;

foreach $key ( sort(keys %wknots) ) {

    if ($key =~ /.vect/) {

	delete $wknots{$key};

    } elsif (!defined($wknots{$key}{mugshot})) {

	print "No mugshot record for $key. We check directory...\n";
	
	$mugname = $knots{$key}{filename};
	$mugname =~ s/vect/a0\.jpg/g;
	
	if (-e $mugname) {

	    print "...found files! Restoring the link.\n";

	    $knots{$key}{mugshot}[0] = $mugname;

	    $mugname =~ s/a0/a1/;
	    $knots{$key}{mugshot}[1] = $mugname;

	    $mugname =~ s/a0/a2/;
	    $knots{$key}{mugshot}[2] = $mugname;

	} else {

	    delete $wknots{$key};

	}

    } elsif (!(-e $wknots{$key}{mugshot}[0]) || !(-e $wknots{$key}{mugshot}[1]) || !(-e $wknots{$key}{mugshot}[2]) ) {

	# This is an error. We should delete this guy's mugshot from the database.

	print("One of the mugshot files $wknots{$key}{mugshot}[0] does not exist for $key.\n");
	print("Deleting the entire array... mkMugshots will regenerate the files.\n"); 

	delete $knots{$key}{mugshot};

	if (defined($knots{$key}{bestside})) { 

	    delete $knots{$key}{bestside};

	}

    } else {

	my $filebase;

	$filebase = $wknots{$key}{filename};
	$filebase =~ s/.vect//;

	if ($wknots{$key}{mugshot}[0] ne $filebase.".a0.jpg") { # doesn't match file

	    print("The mugshot file $wknots{$key}{mugshot}[0] doesn't match the filename $wknots{$key}{filename}. Deleting the record.\n");
	    
	    delete $knots{$key}{mugshot};

	    if (defined($knots{$key}{bestside})) {

		delete $knots{$key}{bestside};

	    }

	}

    }

}

print "Updated knots database. Writing ProposedKnotDB.pl.\n\n";

open(KNOTDB,'>../ProposedKnotDB.pl') or die "Unable to create Knot database.";
print KNOTDB Data::Dumper->Dump([\%knots],['*knots']),"\n";
close KNOTDB;

