#!/usr/local/bin/perl
require "weblib.lib";
$|=1;
use DBI;
&htmlopen("Gallery Verification");
$pictures="/var/www/vhosts/trconnection.com/httpdocs/pictures";
$gallery="$pictures/gallery";
$thumbnails="$pictures/thumbnails";
$dbh=DBI->connect("DBI:mysql:database=trcgallery","todd",'o$fcpsh');
$sth=$dbh->prepare("SELECT * from photoinfo");
$sth->execute();
print "<h2>Missing Photos and Thumbnails</h2>\n";
$count=$skipped=0;
while($info=$sth->fetchrow_hashref()){
	$count++;
	$photo=$info->{'photo'};
	if(!-f "$gallery/$photo"){
		if($info->{caption}=~m%^([-/]|http)%){$skipped++;}
		else{print "Missing photo: $photo - $info->{caption}<br>\n";}
	}
	if($info->{options} ne "visible"){
		print qq{$photo is hidden<img src="/trc/pictures/gallery/$photo" align="top" style="margin: 10px; width: 300px;"><br>\n};
	}
	@photo=split(/\./,$photo);
	$ext=pop(@photo);
	$photo="tn_".(join('.',@photo))."_$ext.jpg";
	if(!-f "$thumbnails/$photo"){print "Missing thumbnail: $photo<br>\n";}
}
print "$count database entries checked<br>\n";
print "$skipped database entries skipped\n";
$filesexpected=$count-$skipped;
$count=0;
$missing=0;
print "<h2>Missing database entries based on file</h2>\n";
opendir(DIR,$gallery);
@files=();
while($file=readdir(DIR)){
	next if $file=~/^\./;
	next if $file=~/^(includes|temp|logo)$/;
	push(@files,$file);
}
foreach $file(sort @files){
	$count++;
	$sth=$dbh->prepare("SELECT * from photoinfo where photo='$file'");
	$sth->execute();
	$info=$sth->fetchrow_hashref();
	if($info->{photo} ne $file){$missing++;print qq{$file<img src="/trc/pictures/gallery/$file" align="top" style="margin: 10px; width: 300px;"><br>\n};}
}
print "$count files checked<br>\n";
print "$filesexpected files expected<br>\n";
print "$missing files missing from database\n";
$count=0;
$missing=0;
print "<h2>Missing database entries based on thumbnail</h2>\n";
opendir(DIR,$thumbnails);
@files=();
while($file=readdir(DIR)){
	next if $file=~/^\./;
	push(@files,$file);
}
foreach $file(sort @files){
	if($file=~/^tn_(.+)_([^_]+)\.jpg$/){
		$photo="$1.$2";
		$count++;
		$sth=$dbh->prepare("SELECT * from photoinfo where photo='$photo'");
		$sth->execute();
		$info=$sth->fetchrow_hashref();
		if($info->{photo} ne $photo){$missing++;print qq{$file<img src="/trc/pictures/thumbnails/$file" align="top" style="margin: 10px;"><br>\n};}
	}
	else{print "Unknown file: $file<br>\n";}
}
print "$count thumbnails checked<br>\n";
print "$missing files missing from database\n";
&htmlclose;
