#!/local/bin/perl

$encfile = "thoth-C++templ";
$tempdir = "/tmp/ato$$";

system("rm","-rf",$tempdir);
( -e $tempdir ) && die "couldn't demolish temporary directory\n";
mkdir($tempdir, 0755) || die "couldn't create temporary directory\n";

( $archive, @objs ) = @ARGV;

if ( -e $encfile ) {
	print "Hey, what is the file $encfile doing around here?\n";
	print "Get it out of the way before you run $0.\n";
	exit 1;
}

$i=0;
$rval =system("/usr/bin/ar","x",$archive, $encfile) /256 ;
if (0!=$rval || ! -e $encfile) {
	print "archive didn't have an encoding file, creating\n";
	open(ENC,">$encfile");
	close(ENC);
} elsif ( ! -w $encfile ) {
	die "can't write to $encfile\n";
} else {
	open(ENC,"<$encfile") || die "couldn't open $encfile for read";
	while($_=<ENC>) {
		chop;
		$MAPPING{$_} = $i;
		$i++;
	}
	close(ENC);
}

open(ENC,">>$encfile") || die "couldn't open $encfile for append";

foreach (@objs) {
	( $clean = $_ ) =~ s-^.*/--;
	$num = $MAPPING{$clean};
	if ( $num eq "" ) {
		$num = $i++;
		$MAPPING{$clean} = $num;
		#print "creating new mapping $clean -> $num\n";
		print ENC $clean,"\n";
	}
	$newfilename = $tempdir."/".$num.".o";
	@files = ( @files, $newfilename );
	system("cp",$_,$newfilename);
	#print "$_ -> $newfilename\n";
}
close(ENC);

$rval = system("/usr/bin/ar","rv",$archive, $encfile, @files);
if ($rval != 0) {
	print "$0: Failed system call:\n";
	print "ar rv $archive $encfile ",join(" ",@files),"\n";
}

unlink ($encfile);

system("rm", "-rf", $tempdir);
