#!/usr/bin/perl -w

# Hard-link files from the source directory into the passed directory,
# in the right secion. This is kind of an optimized ln that doesn't
# read the directory N thousand times.

use strict;
use File::Path 'make_path';

my $tgdir = $ARGV[0];
die "Missing argument" unless defined($tgdir);

# read the existing rfcs
opendir(my $dh, '..') || die "Can't opendir ..: $!";
my @entries = readdir($dh);
my %files = map { $_ => 1 } @entries;
closedir $dh;

# compute a hash rfc to target directory, to avoid list scanning later
open(my $fh, '<', "rfc-status.txt") or die $!;
my %equiv;
while(<$fh>) {
    my ($rfc, $dir) = split;
    $equiv{int($rfc)} = $dir;
}

# create needed dirs, once
my %paths;
foreach my $path (values %equiv) {
    $paths{$path} = 1;
}
foreach my $dir (keys %paths) {
    make_path("$tgdir/$dir");
}

# and now create the links, scanning the existing rfc list only once
foreach my $src (@entries) {
    if(! ($src =~ /^rfc(\d+)\./o)) {
        next;
    }
    my $rfcid = int($1);
    my $dir = $equiv{$rfcid};
    next unless(defined($dir));
    #print "will make link for $src ($rfcid) to '$tgdir/$dir'\n";
    # Convert Postscript files to PDF, since PS later
    # parsing/displaying is problematic.
    if ($src =~ /.*\.ps$/) {
        my $pdf = $src;
        $pdf =~ s/\.ps$/.pdf/;
        if (exists($files{$pdf})) {
            print " - skipping PostScript file '$src' as there exists a PDF version\n";
        } else {
            print "- converting $src postscript file to $pdf\n";
            my @args = ("ps2pdf", "../$src", "$tgdir/$dir/$pdf");
            system(@args) == 0
                or die "system @args failed: $?";
        }
    } else {
        link("../$src", "$tgdir/$dir/$src")
            or die "Can't create link: $!";
    }
}
