#!/usr/bin/perl
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  renamecachefiles -
#
#SYNOPSIS
#  find ... | renamecachefiles 
#
#REQUIRES
	require "Backup.pm";
#
#DESCRIPTION
#  Rename files in the abcbot cache.  This is to convert an older naming
#  convention to the current naming convention.
#
#  This version strips out _ chars and final articles, and converts letters
#  to upper case.  
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

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

$files = 0;			# Count of files renamed
for $path (<STDIN>) {
	$path =~ s/[\r\s]+$//;
	print STDERR "$P: path='$path'\n" if $V>1;
	&onename($path);
}

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

sub onename {my $F='onename';
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	local($pth) = @_;
	local($dir,$fil,$new);
#	$pth =~ s/[\r\s]*$//;
	unless (($dir,$fil) = ($pth =~ m"^(.*)/([^/]+)$")) {
		print STDERR "$F: Can't parse '$pth'\n" if $V>0;
	}
	if ($fil =~ /-$/) {
		print STDERR "$F: Backup file '$fil'\n" if $V>0;
		return;
	}
	if ($fil =~ /^%/) {
		print STDERR "$F: Ignore file '$fil'\n" if $V>0;
		return;
	}
	unless ($dir =~ /:$/) {
		print STDERR "$F: Dir '$dir' lacks final ':'\n" if $V>0;
		return;
	}
	unless ($fil =~ /^(\d+):/) {
		print STDERR "$F: No \d: in '$fil'\n" if $V>0;
		return;
	}
	$fil =~ s/_the$//i;
	$fil =~ s/_an*$//i;
	$fil =~ s/_//g;
	$fil = uc($fil);
	$fil =~ s/^(\d+):(.*)/%$1:$2/;
	print "$P: fil='$fil'\n" if $V>2;
	$new = "$dir/$fil";
	print "$P: new= '$new'\n" if $V>1;
	Backup($new) if -f $new;	# Only during debugging
	unless (link($pth,$new)) {
		print STDERR "$F: Can't link '$pth' -> '$new' [$!]\n" if $V>0;
		return;
	}
	++$files;
	Backup($pth);		# Rename original tune as a backup
#	unless (unlink($pth)) {
#		print STDERR "$F: Can't unlink '$pth' [$!]\n" if $V>0;
#	}
}
