#!/usr/bin/perl
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  lnabc -
#
#SYNOPSIS
#  lnabc [dir]..
#
#REQUIRES
	push @INC, ".", "$ENV{HOME}/sh";
	require "Backup.pm";
#
#DESCRIPTION
#  Search the directories for "*.abc" files, and link them here  under  their
#  parent directories' names.
#
#  This is used to "capture" the source files from a subset of the ABC  bot's
#  cache  directories  (~/bot/http)  by linking them into a single directory.
#  This gives us an extract from the cache, with all the source  files  in  a
#  single  directory.   We  can  then process those source files with further
#  programs.
#
#  The resulting file names will generally  be  the  original  files'  names,
#  minus the directory info. Name collisions are to be expected, and they are
#  handled by using Backup() to append hyphens to the file names.
#
#OPTIONS
#
#EXAMPLES
#  : cd ~/abc/mirror
#  : mkdir foo.com
#  : cd foo.com
#  : lnabc ~/bot/http/foo.com/~joe
#  This makes a "mirror" directory, finds all the cached abc source files  in
#  foo.com/~joe, and links them into the mirror directory.
#
#FILES
#
#BUGS
#  This is a very special-purpose program, and will change occasionally as  I
#  find  slightly  different things that I want it to do.  I haven't tried to
#  make it very general, because most of its uses are one-shot  events.   But
#  it's  sufficiently  useful  and  complex to be worth keeping around rather
#  than rewriting each time.
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

$| = 1;
$exitstat = 0;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 1;	# Verbose level.

arg:
for $dir (@ARGV) {
	print "=== $dir ===\n" if $V>0;
	$cmd = "find $dir -name '*.abc'";
	print "$P: cmd=\"$cmd\"\n" if $V>2;
	unless (open(CMD,"$cmd |")) {
		print STDERR "$0: Can't run \"$cmd\" ($!)\n" if $V>1;
		next arg;
	}
	$files = 0;		# Count the successful links from each dir
	for $abc (<CMD>) {
		$abc =~ s/[\r\s]+$//;
		print "$P: abc='$abc'\n" if $V>1;
		if (($pth,$fil) = ($abc =~ m"^(.*)/([^/]*\.abc)$")) {
			print "$P: --> '$fil'\n" if $V>1;
			if (-f $fil) {
				Backup($fil);
			}
			$cmd = "/bin/ln '$abc' '$fil'";
			print "$P: cmd=\"$cmd\"\n" if $V>2;
			if (system $cmd) {
				print STDERR "$P: Can't link '$abc'->'$fil' ($!)\n" if $V>0;
			} else {
				system "ls -ld $fil*" if $V>1;
				++$files;
			}
		} else {
			print STDERR "$P: Can't parse '$abc'\n" if $V>1;
		}
	}
	print "\t$files.\n" if $V>0;
}

print "$P: Exit with status $exitstat.\n" if $V>1;
exit $exitstat;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
