#!/usr/bin/perl
use strict;

my $debug	= 0;

my $max_links	= 515;

chdir "/www/screenshots/KSP";

opendir DIR, '.';
while (my $fn = readdir DIR)  {
	if ($fn =~ /\.png$/) {
		my $new = $fn;
		$new =~ s/\.png/\.jpg/;
		#print "convert $fn -quality 60 $new\n";

		#system("convert",$fn,"-resize","1920x1920","-quality","60",$new);
		system("convert",$fn,"-quality","60",$new);
		system("mv",$fn,"png/");
	}
}
close DIR;

my @files = ();

opendir DIR, '.';
while (my $fn = readdir DIR)  {
	if ($fn =~ /^KSP_x64\ \d+-\d+-\d+.*\.jpg$/) {
		my $new = $fn;
		$new =~ s/KSP_x64/KSP/;
		system("mv",$fn,$new);
	}
}

# Do this separately
opendir DIR, '.';
while (my $fn = readdir DIR)  {
	if ($fn =~ /^(KSP|NMS)\ \d+-\d+-\d+.*\.jpg$/) {
		if (-l $fn) {
			#print "remove symlink $fn\n";
			unlink $fn if (!$debug);
		} elsif (-e $fn && -f $fn) {
			push @files,  $fn;
		}
	}
}
close DIR;

my $count = 0;

foreach my $fn (sort { $a cmp $b } @files) {

	if ($fn =~ /(KSP|NMS)\s(\d+)-(\d+)-(\d+)\s/) {
		my $path = "$2-$3";
		my $game = $1;

		my $dir = '/www/ksp.necrobones.com/screenshots';
		$dir = '/www/necrobones.com/nomanssky/screenshots' if ($game eq 'NMS');

		my $altpath = '';
		$altpath = "../$game/" if ($game && $game ne 'KSP');

		print "$fn -> $dir/$path\n";

		next if (!-e $fn || !-f $fn || -l $fn);

		if (!$debug) {
			#system('mkdir','-p',$path) if (!-d $path);
			system('mkdir','-p',"$altpath$path") if (!-d "altpath$path");
			system('ssh','-p','222','services',"mkdir -p $dir/$path");
			system('scp','-P','222',"$fn","services:$dir/$path/");
			system("mv",$fn,"$altpath$path/");
			$count++;
		}
	}
}

if ($count) {
	#system("chown -R www:www 20*.png");
	system("ssh -p 222 services 'chown -R www:www /www/ksp.necrobones.com/screenshots/*'");
	system("ssh -p 222 services 'chown -R www:www /www/necrobones.com/nomanssky/screenshots/*'");
}

my %hash = scan_path('.');

sub scan_path {
	my $path = shift;

	my @dirs = ();

	opendir DIR, $path;
	while (my $fn = readdir DIR)  {
		next if ($fn =~ /^\./);

		if ($fn =~ /^\d/ && -d "$path/$fn") {		# Process date folders only
			push @dirs, "$path/$fn";
		} elsif (-e "$path/$fn") {
			$hash{$fn} = "$path/$fn";
		}
	}
	closedir DIR;

	foreach my $d (@dirs) {
		my %tmp = scan_path($d);
		foreach my $f (keys %tmp) {
			$hash{$f} = $tmp{$f};
		}
	}

	return %hash;
}

my $n = 0;

foreach my $fn (sort { $b cmp $a } keys %hash) {

	next if ($fn !~ /^KSP\s\d+-\d+-\d+\s.*\.jpg$/i);

	if ($n < $max_links) {
		#print "symlink $hash{$fn} .\n";
		system('ln','-s',$hash{$fn},$fn) if (!$debug);
	} else {
		last;
	}
	$n++;
}

exit;

