#!/usr/bin/perl
# 2010-06-09, Craig Weinhold (cweinhold@gmail.com)

use strict;

my $junction = 'junction.exe';		# where junction.exe is located (default = same directory)
my $sep = ', ';				# what to use as a separator

if (! -x $junction) {
	print "Download sysinternals' junction.exe from http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx and place it in the same directory as this script\n";
	exit 0;
}

my $source = shift @ARGV;
my $target = shift @ARGV;
my $extra = shift @ARGV;
my $stems = {};

if ($source =~ /^-d/) {
	&purgeJunctions($target);
	exit 0;
}

$source =~ s/[\/\\]+$//;

if (! -d $source) {
	print <<EOT;
Usage:	$0 <source-directory> <target-directory> [top-level-string]
	$0 -d <target-directory>
EOT
	exit 0;
}

if (! -d $target) {
	`mkdir $target`;
	if (! -d $target) {
		print "Could not create target $target\n";
		exit 0;
	}
}


&recurse($source);

foreach (sort keys %$stems) {
	my $new = ($extra) ? "\\$extra$_" : $_;
	$new =~ s#^\\##;			# trim first slash
	$new =~ s#\\#$sep#g;		# change slashes to dashes

	my $exists = (-d "$target\\$new");

	print sprintf("%-70s", "$_ (" . $stems->{$_}->{count} . " photos)") .
		" -> $new" . (($exists) ? " (exists)\n" : "\n");

	if (! $exists) {
		`$junction \"$target\\$new\" \"$source$_\"`;
	}
}

exit 0;

sub recurse
{
	my ($root, $stem) = @_;
	my $dir = $root . $stem;

	opendir(DIR, $dir); my @files = readdir(DIR); closedir(DIR);

	foreach my $f (@files) {
		if ( ($f !~ /^\./) && (-d "$dir\\$f") ) {
			&recurse($root, "$stem\\$f");
		}
		elsif ( ($f =~ /\.[jpg|jpeg]/i) && (-f "$dir\\$f") ) {
			$stems->{$stem}->{count}++;
		}
	}
}

sub purgeJunctions
{
	my $dir = shift;

	opendir(DIR, $dir); my @files = readdir(DIR); closedir(DIR);

	foreach (@files) {
		next if ( (/^\./) || (! -d "$dir\\$_") );
		my $jtest = `$junction "$dir\\$_"`;
		if ($jtest =~ /Substitute Name/) {
			print "removing junction $_\n";
			`$junction -d "$dir\\$_"`;
		}
	}
}
