#!/usr/bin/perl -w

$prog = $0;
$prog =~ s@.*/@@;

$strip_command = "strip --remove-section=.comment --remove-section=.note";

use Getopt::Std;
use vars qw($opt_h $opt_s);

getopts("hsw:W:");

if ($opt_h) {
	usage(0);
}
if ($#ARGV < 0) {
	usage(1);
}

foreach $input (@ARGV) {
	my $magic;

	open(INPUT, $input);
	read(INPUT, $magic, 8);
	close(INPUT);

	if (substr($magic, 0, 4) eq "\177ELF") {
		&do_object($input);
	}
	elsif (substr($magic, 0, 7) eq "!<arch>") {
		&do_archive($input);
	}
	else {
		next;
	}

	if ($opt_s) {
		system("$strip_command $input >/dev/null 2>&1");
	}
}

sub do_object {
	my ($file) = @_;
	my $comment;
	local $/ = undef;

	if (! open(COMMENT, "elfcat .comment $file 2>/dev/null |")) {
		die "$prog: elfcat program not found\n";
	}
	$comment = <COMMENT>;
	close(COMMENT);

	test_comment($file, $comment);
}

sub do_archive {
	my ($file) = @_;
	my $comment;
	my $tmp;
	my @members;
	local $/;

	$comment = '';
	$tmp = "/tmp/elfcat.$$";
	undef @members;

	$/ = "\n";
	open(AR, "ar t $file |");
	while (<AR>) {
		chomp;
		push(@members, $_);
	}
	close(AR);

	$/ = undef;
	foreach $object (@members) {
		system("ar p $file $object > $tmp");
		if (! open(COMMENT, "elfcat .comment $tmp 2>/dev/null |")) {
			die "$prog: elfcat program not found\n";
		}
		$comment .= <COMMENT>;
		close(COMMENT);
		unlink($tmp);
	}
	test_comment($file, $comment);
}

sub test_comment {
	my ($file, $comment) = @_;
	my @comment;

	$comment =~ s/^\000*//;
	$comment =~ s/\000*$//;
	@comment = split(/\000+/, $comment);
	@comment = uniq_gcc(sort(@comment));
	if ($#comment > 0) {
		print "$prog: $file: " . ($#comment + 1) . " GCC versions used\n";
	}
	elsif ($#comment == 0) {
		if ($opt_w && $comment[0] !~ /$opt_w/) {
			print "$prog: $file: not compiled with $opt_w GCC\n";
		}
		if ($opt_W && $comment[0] =~ /$opt_W/) {
			print "$prog: $file: compiled with $opt_W GCC\n";
		}
	}
	else {
		print "$prog: $file: has no .comment\n";
	}
}

sub uniq_gcc {
	my @uniq;
	my $previous;
	my $current;

	undef @uniq;
	foreach $current (@_) {
		next if (defined($previous) && $current eq $previous);
		push(@uniq, ($previous = $current)) if $current =~ /^GCC/;
	}
	return @uniq;
}

sub usage {
	$status = shift;

	$out = $status ? STDERR : STDOUT;
	print $out <<EOF;
usage: $prog [files]

test and optionally strip ELF files

 -h         print this help
 -w REGEX   want GCC version to match this REGEX
 -W REGEX   do not want GCC version to match this REGEX
 -s         strip files
EOF
	exit($status);
}
