#!/usr/bin/perl -w

$| = 1;
$exitstat = 0;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 2;	# Verbose level.
$mv = ($P =~ /^mv/i) ? 1 : 0;	# Just linking or moving?

@dirs = ();	# Where to link files

for $fil (@ARGV) {
	if (-d $fil) {
		push @dirs, $fil;
	} else {
		if ($fil =~ m"^(.*/)(.*)$") {	# Path or file name?
			$pth = $1;	# Path to file's current directory
			$nam = $2;	# Name of file in target directory
		} else {
			$pth = '';
			$nam = $fil;
		}
		print "$P: pth='$pth' nam='$nam'\n" if $V>2;
		for $dir (@dirs) {
			if (link($fil,"$dir/$nam")) {
				print "$P: Linked '$fil' to '$dir/$nam'\n" if $V>2;
				if ($mv) {	# If moving, get rid of old file
					if (unlink($fil)) {
						print "$P: Unlinked '$fil'\n" if $V>2;
					} else {
						print STDERR "$P: Can't unlink '$fil' [$!]\n";
						$exitstat = int($!);
					}
				}
			} else {
				print STDERR "$P: Can't link '$fil' to '$dir/$fil' [$!]\n";
			}
		}
	}
}

exit $exitstat;
