#!/usr/bin/perl -w

# 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);
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";
    link("../$src", "$tgdir/$dir/$src") || die "Can't create link: $!";
}
