#!/usr/bin/perl

use strict;
use warnings;

if (!defined $ARGV[0] || !-d $ARGV[0])
{
    &printUsage('Missing source directory');
}
my $source_dir = $ARGV[0];
if (!defined $ARGV[1] || !-d $ARGV[1])
{
    &printUsage('Missing target directory');
}
my $target_dir = $ARGV[1];

print "====== Linkinator ======\n";
print "Replaces files in <target dir> with links if they are also found in\n";
print "<source dir>.\n\n";
&recursivelyScan($source_dir, $target_dir);
print "====== Complete! ======\n\n";
exit;

sub printUsage
{
    my ($msg) = @_;
    if (defined $msg)
    {
        print "Error! $msg\n"; 
    }
    print "Usage: linkinator.pl <source dir> <target dir>\n\n";
    exit;
}

sub recursivelyScan
{
    my ($sdir, $tdir) = @_;

    print " * Comparing: " . $tdir . " => " . $sdir . "\n";

    opendir(DH, $tdir);
    my @files = readdir(DH);
    closedir(DH);
    
    foreach my $file (@files)
    {
        if ($file !~ /^\./)
        {
            my $spath = $sdir . '/' . $file;
            my $tpath = $tdir . '/' . $file;
            if (-d $tpath && -d $spath)
            {
                &recursivelyScan($spath, $tpath);
            }
            elsif (-f $tpath && -f $spath)
            {
                print " - symlinking: " . $file . "\n";
                unlink($tpath);
                link($spath, $tpath);
            }
            elsif (-f $tpath)
            {
                print " - only in target: " . $file . "\n";
            }
        }
    }
}
