#!/local/bin/perl

#  This perl script originally used an encoding file that was part of
# the archive.  Solaris couldn't stomach this.  Now it uses an external
# file.


sub do_ar {
    local(@files) = @_;


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

$encfile = "../ar-remangling";
$tempdir = "/cis/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";

$ar_args="";
if ($ARGV[0] =~ /^-/) {
    $ar_args = $';
    shift;
}

( $archive, @objs ) = @ARGV;

if (@objs==0) {
    print "No objects specified on command line.  Reading from stdin.\n";
    @objs=<STDIN>;
    foreach (@objs) { chop; }
}

if ( 0 && -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;

# Solaris doesn't like archives that contain non-.o files
#$rval =system("ar","x",$archive, $encfile) /256 ;
$rval = 0;

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);

local ($len, @temp)=(0);

for ($i=0; $i<@files; $i++) {
    if ($len + 4 + length($files[$i]) < 4000) {
	push(@temp, $files[$i]);
	$len += 4 + length($files[$i]);
    } else {
	&do_ar(@temp);
	$len =0;
	@temp=();
    }
}
if (@temp) {
	&do_ar(@temp);
}

# unlink ($encfile);

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