#!/usr/bin/env perl

use strict;

use File::Spec::Functions;

$| = 1;

my $iDir = $ARGV[0] or usage("No input directory specified...");
my $iCopied = $ARGV[1] or usage("No input copy file specified...");
my $oFile = $ARGV[2] or usage("No output file specified...");

openFoafList($oFile);
getFoafList($iDir);
copyList($iCopied);
closeFoafList();

sub copyList
{
    my $fn = shift;
    open COPY,"<$fn" or die "Cannot open $fn $!\n";
    print "Copying external foaf locations from $fn\n";
    while(<COPY>){
        if (m/<location/){
            s!\\!/!g;
            print OUT;
         }
    }
    close COPY;
}

sub getFoafList
{
    my $dir = shift;
    opendir(my $dh, $dir) or die "Couldn't open '$dir'\n$!\n";
    print "Collecting foaf locations from '$dir'\n";
    while (my $f = readdir($dh)) {
        next if $f =~ /^\./;
        if ($f =~ /\.rdf$/) {
            writeFoafEntry(catfile($dir, $f));
        }
    }
    closedir($dh);
}

sub openFoafList
{
    my $foafListFn = shift;
    print "Creating foaf location list file '$foafListFn'\n";
    open(OUT, ">$foafListFn") or die "Unable to open '$foafListFn' for".
                                     " writing.\n$!";
    
    print OUT <<EOT;
<?xml version="1.0"?>
<list>
EOT
}

sub writeFoafEntry
{
 # N.B. It seems that xsltproc on Windows ignores any entries containing "\"
 # Also, file: locations must start with file:///[drive:]/ or file:///..
 # 
    my $file_pfx='file://'; # default prefix - but should this also be file:/// ?
    if ($^O =~ /^MSWin32/){
        $file_pfx='file:///'; # Use corrected file prefix
    }

    my $u=shift;
    if ($^O =~ /^MSWin32/){
        $u =~ s!\\!/!g; # convert \ to /
    }
    print OUT  "  <location>$file_pfx$u</location>\n";
}

sub closeFoafList
{
    print OUT "</list>\n";
    close OUT; # Done with the file
}

sub usage
{
    my $msg = shift;
    print <<EOF;

$0 Usage:
	$0 <input directory> <output file>

Error:
EOF
    die "$msg\n";
}
