#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  relinkdirs -
#
#SYNOPSIS
#  relinkdirs [dir]..
#
#REQUIRES
#
#DESCRIPTION
#  Do a depth-first search of the  directories.   For  each  directory,  call
#  relink  for  the  files  in that directory.  The result will be converting
#  multiple identical files in a directory into links to a single file.
#
#  Identical files in different directories aren't compared by this  program.
#  Use relink itself if you want to do that, which takes a lot longer, but is
#  a lot more thorough.
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu> May 2010.
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #

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

for $d (@ARGV) {
	if (-d $d) {
		++$dirs;
		&onedir($d);
	} else {
		print "#### $d is not a directory.\n" if $V>0;
		$exitstat = 1;
	}
}
unless ($dirs > 0) {
	++$dirs;
	&onedir('.');
}

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

sub onedir {my $F='onedir'; local($dir) = @_;
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
	local($cmd,$fil,@files,$path,@save);
	print "DIR: $dir\n" if $V>1;
	unless (opendir(DIR,$dir)) {
		print STDERR "$P: ### Can't read \"$dir\" [$!]\n" if $V>0;
		return;
	}
	print "$F: Read \"$dir\" ...\n" if $V>2;
	@files = readdir(DIR);
	for $fil (@files) {
		next if $fil eq '.';
		next if $fil eq '..';
		$path = "$dir/$fil";
		if (-d $path) {
			++$dirs;
			&onedir($path);
		} elsif (-f $path) {
			push @save, "'$path'";
		} else {
			print "--- Ignore non-file, non-dir \"$path\"\n" if $V>1;
		}
	}
	if (@save) {	# Files in this directory
		print "---> $dir\n" if $V>2;
	#	$cmd = "relink +rv$V $dir";
		$cmd = "relink +v$V " . join(' ',@save);
		system $cmd;
	}
	print "===> $dir\n" if $V>0;
	$cmd = "relink +rv$V '$dir'";
	system $cmd;
}

