#!/usr/bin/perl -w

# Identify and delete orphaned photos.

use lib "../src";
use lib "./cms/src";
use strict;
use Siikir;
use Siikir::Util;
chdir("../..");

my $cms = Siikir->new(
	debug => 1,
	root  => "./cms",
);
$cms->loadPlugin("JsonDB");
$cms->loadPlugin("User");
$cms->loadPlugin("Photo");

# Get all photo names.
my %dirlist = ();
opendir (my $dir, "./static/photos");
foreach my $file (sort(grep(/\.(jpe?g|gif|png)$/i, readdir($dir)))) {
	$dirlist{$file} = 1;
}
closedir($dir);

# fix missing photo sizes
my @fixed = ();

my $users = $cms->User->listUsers();
foreach my $user (@{$users}) {
	print "User ID: $user\n";
	my $albums = $cms->Photo->getAlbums($user, 1);
	foreach my $album (@{$albums}) {
		print "\tAlbum: $album->{name}\n";
		my $photos = $cms->Photo->getAlbum($user, $album->{name}, 1);

		# Recalc each smaller photo.
		foreach my $photo (@{$photos}) {
			print "\t\tPhoto: $photo->{key}\n";

			# Scale each smaller size.
			foreach my $size (qw(large medium small tiny avatar mini)) {
				# Remove this photo from the dirlist.
				my $file = $photo->{$size};
				if (!exists $dirlist{$file}) {
					print "Warning: didn't see $file in the directory!\n";

					# Fix this missing photo.
					if (length $photo->{large}) {
						$file = $cms->Photo->resizePhoto("./static/photos/$photo->{large}", $size);
						$cms->Photo->updatePhoto ($user, $photo->{key}, $size => $file);
						push (@fixed, "Generated photo size $size for user $user (key $photo->{key}) (new name: $file) [$@]");
					}
					else {
						push (@fixed, "Missing photo size $size for user $user (and no large size either!)");
					}
					<STDIN>;
					next;
				}
				delete $dirlist{$file};
			}
		}
	}
}

if (scalar(@fixed)) {
	print "\nSome photos were fixed:\n" . join("\n", @fixed) . "\n";
}

print "\nThere are " . (scalar(keys(%dirlist))) . " orphaned photos:\n";
foreach my $key (sort keys %dirlist) {
	print "\t$key\n";
}

if (scalar keys %dirlist > 0) {
	print "Delete these? [yN] ";
	chomp(my $ans = <STDIN>);
	if ($ans eq "y") {
		foreach my $key (keys %dirlist) {
			unlink("./static/photos/$key");
		}
	}
}
