#!/usr/bin/perl
#
#NAME
# lnto - Link files to directories
#
#SYNOPSIS
# lnto [file].. [dir].. [type]..
#
#DESCRIPTION
# This is what I use to "classify" music files by linking them to directories
# with names that are the classification types. The args may be in any order.
# Those that are files will be linked into all the directories  that  can  be
# discovered by combining the rest of the args in various orders.
#
#SETUP
# You may want to change any of these:
#
# The basedirs list should be full paths to  one  or  more  directories  that
# contain the directories that you want to link into:
	@basedirs = ("$ENV{HOME}/abc");
#
# The lncmd is the command used to link a file.  It will only be called  with
# two pathnames (which may not be full paths).
#	$lncmd = 'Lc';
#	$lncmd = 'Ln';
	$lncmd = 'ln -f';
#
#OPTIONS
# None, so far.
#
#EXAMPLES
#
# lnto PhousJig.abc BharresFav.abc Scotland England Contra jig
#   On my home machine, this will discover that there are directories:
#     $ENV{HOME}/abc/jig/
#     $ENV{HOME}/abc/Scotland/jig/
#     $ENV{HOME}/abc/England/jig/
#     $ENV{HOME}/abc/Contra/jig/
#   The program will link the two *.abc files into all four of these
#   directories.
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
# John Chambers <jc@trillian.mit.edu>

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

for $a (@ARGV) {
	if (-f $a) {
		push @files, $a;	# Files to link
	} elsif ($a =~ /^[A-Z]/) {
		push @Ucdir, $a;	# Area names
	} elsif ($a =~ /^[a-z]/) {
		push @lcdir, $a;	# Rhythm names
	}
}

# Find directories
for $base (@basedirs) {
	print "Base Dir \"$base\"\n" if $V>2;
	for $Ucd (@Ucdir) {
		for $lcd (@lcdir) {
			&tstdir("$lcd");
			&tstdir("$Ucd/$lcd");
			&tstdir("$base/$lcd");
			&tstdir("$base/$Ucd/$lcd");
		}
	}
}

#for $d (@dirs) {
#	for $f (@files) {
#		print "LN: $f -> $d/$F\n";
#	}
#}


exit 0;

sub tstdir { my $F='tstdir';
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	local($d) = @_;
	local($n,$p);
	if (-d $d) {
		print "$F: \"$d\" is a directory.\n" if $V>2;
		for $f (@files) {			# Files to be linked into directory
			($n = $f) =~ s"^.*/"";	# File name without directory path
			$p = "$d/$n";			# Path it's to be linked to
			if (-f $p) {
				print "x\t$p EXISTS\n" if $V>0;
			} else {
				system "$lncmd $f $p";
				print "->\t$p\n" if $V>0;
			}
		}
	} else {
		print "$F: \"$d\" is not a directory.\n" if $V>3;
	}
}
