#!/usr/bin/perl -w

#
# Clean up discrepancies bewteen the db and the images.
#
# jgeiger, Jan 2003
#

use strict;
use DBI;

my $db_host = "localhost";
my $db_name = "zoph";
my $db_user = "zoph_rw";
my $db_pass = "pass";
my $db_prefix = "zoph_";

my $image_dir = "/data/images";

my $type = $ARGV[0];
if (!$type or ($type ne "-file" and $type ne "-db")) {
    die "zophClean: please specify -file or -db\n";
}

my $dbh = DBI->connect("DBI:mysql:$db_name:$db_host", $db_user, $db_pass) or die "$!";
my $query = "select distinct(concat(concat(path, '/'), name)) from $db_prefix" . "photos order by path, name";
my $sth = $dbh->prepare($query);
$sth->execute() or die "$!";

my @db_images;

while (my ($image) = $sth->fetchrow_array()) {
    #print "$image_dir/$image\n";
    push @db_images, "$image_dir/$image";
}

$dbh->disconnect();

open IMAGES, "find $image_dir -iname \"*.jpg\" | fgrep -v mid_ | fgrep -v thumb_ | sort | uniq |" or die "$!";

my @file_images = <IMAGES>;
close IMAGES;

if ($type eq "-file") {
    print "echo ";
}
elsif ($type eq "-db") {
    print "# ";
}

print scalar @file_images, " files, ", scalar @db_images, " records\n";

my $image = shift @file_images;
my $db_image = shift @db_images;

while (1) {
    if (not $image or not $db_image) { last; }

    chomp $image;

    if ($image ne $db_image) {
        if ($image lt $db_image) {
            if ($type eq "-file") {
                print "rm $image; ";
                $image =~ s|/([^/]+)$|/mid/mid_$1|;
                print "rm -f $image; ";
                $image =~ s|mid|thumb|g;
                print "rm -f $image\n";
            }
            $image = shift @file_images;
        }
        else {
            if ($type eq "-db") {
                my $image_name = $db_image;
                $image_name =~ s/.*\/([^\/]+)/$1/;
                my $image_path = $db_image;
                $image_path =~ s/\Q$image_dir\E\/(.*)\/\Q$image_name/$1/;
                print "delete from $db_prefix" . "photos where name = '$image_name' and path = '$image_path';\n";
            }
            $db_image = shift @db_images;
        }
    }
    else {
        $image = shift @file_images;
        $db_image = shift @db_images;
    }
}

if ($type eq "-file") {
    while (my $image = shift @file_images) {
        print "rm $image; ";
        $image =~ s|/([^/]+)$|/mid/mid_$1|;
        print "rm -f $image; ";
        $image =~ s|mid|thumb|g;
        print "rm -f $image\n";
    }
}
elsif ($type eq "-db") {
    while (my $image = shift @db_images) {
        my $image_name = $db_image;
        $image_name =~ s/.*\/([^\/]+)/$1/;
        my $image_path = $db_image;
        $image_path =~ s/\Q$image_dir\E\/(.*)\/\Q$image_name/$1/;
        print "delete from $db_prefix" . "photos where name = '$image_name' and path = '$image_path';\n";
    }
}
