#!/usr/bin/env perl
# This is like /usr/bin/install, but also checks whether the
# source has an associated .GCCABI2 file, and installs that too
# if necessary.
use strict;
use FindBin qw($RealBin);
use File::Spec;

my $source; # source filename
my $index;  # index in the parameter array which contains $source

# Get the source filename
for (my $i = 0; $i < @ARGV; $i++) {
	if ($ARGV[$i] =~ /^-[gmos]$/) {
		# Parameter that requires another parameter
		$i++;

	} elsif ($ARGV[$i] eq '--') {
		$source = $ARGV[$i + 1];
		$index = $i + 1;
		last;

	} elsif ($ARGV[$i] =~ /^-/) {
		# Parameter, do nothing

	} else {
		$source = $ARGV[$i];
		$index = $i;
		last;
	}
}


##
# run(print, argv...)
#
# Run a command. Exit if the command failed.
#
# print: whether the command should be printed to screen.
# argv: the command to run.
sub run {
        my $print = shift;
        print "@_\n" if ($print);
	my $status = system(@_);
	exit 127 if ($status == -1);
	exit($status / 256) if ($status != 0);
}


# Install the original binary.
run(1, "install", @ARGV);

my $dest = $ARGV[$index + 1];
if (defined $source && -x "$source" && -f "$source.GCCABI2" && defined $dest) {
	# There is a corresponding .GCCABI2 file for this binary.
	# Install it.

	$ARGV[$index] = "$source.GCCABI2";

	# $dest may not be a folder name, so process it.
	if (! -d $dest) {
		my (undef, $dir) = File::Spec->splitpath($dest);
		my (undef, undef, $file) = File::Spec->splitpath($source);
		$ARGV[$index + 1] = "$dir/$file.GCCABI2";
	}

	run(1, "install", @ARGV);
}
