#!/nw/dev/u/bin/perl -w

use strict;
use Getopt::Std;
use IO::File;
use File::LinkTree;

sub usage {
    print 
"usage: linktree [-n] [-v] [-m 0777] [-u] (<src>|-f LINKTREES) <dest>
         -f <trees>    link all the directories listed in <trees>
         -m <mode>     create directories with <mode>
         -u            unlink
         If \$LINKTREE_BASE is set, <dest> may be omitted.

       linktree -p [-n] [-v] [-f LINKTREES] <dir>
         -f <trees>    write a list of all directories linked into <dir>
         -p            prune bad links under <dir> (or \$LINKTREE_BASE)

         -n            no operation mode
         -s            silent (don't warn about minor problems)
         -v            verbose
";
    exit 0;
}

my $opt = {};
getopts("f:m:upnv", $opt) or &usage;

$opt->{nop} = $opt->{n};
$opt->{verbose} = $opt->{v};

if (! $opt->{p}) {
    my $part2 = sub {
	my ($opt) = @_;
	&usage if (!$opt->{src} or !$opt->{dest} or @ARGV);
	symlink_tree($opt);
    };

    $opt->{mode} = $opt->{'m'};
    $opt->{'unlink'} = $opt->{u};
    $opt->{dest} = $ENV{LINKTREE_BASE} if $ENV{LINKTREE_BASE};
    if ($opt->{f}) {
	$opt->{dest} = shift @ARGV if @ARGV;
	my $fh = new IO::File;
	$fh->open($opt->{f}) or die "open $opt->{f}: $!";
	while (defined(my $dir = <$fh>)) {
	    chomp $dir;
	    $opt->{src} = $dir;
	    $part2->($opt);
	}
    } else {
	$opt->{src} = shift @ARGV;
	$opt->{dest} = shift @ARGV if @ARGV;
	$part2->($opt);
    }
} else {
    &usage if ($opt->{'m'} or $opt->{u});
    $opt->{dir} = $ENV{LINKTREE_BASE} if $ENV{LINKTREE_BASE};
    $opt->{dir} = shift @ARGV if @ARGV;
    $opt->{trees} = $opt->{f} if $opt->{f};
    &usage if @ARGV;
    prune_tree($opt);
}
