#!/usr/bin/perl -w

#
# Profiler utility (generates map of imageids of binaries and libraries, plus kernel info)
#
# Copyright (c) Compaq Computer Corporation, 1999
#
# Use consistent with the GNU GPL is permitted,
# provided that this copyright notice is
# preserved in its entirety in all copies and derived works.
#
# COMPAQ COMPUTER CORPORATION MAKES NO WARRANTIES, EXPRESSED OR IMPLIED,
# AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR ITS
# FITNESS FOR ANY PARTICULAR PURPOSE.
#
#      Author          Deborah A. Wallach
#                      Compaq Western Research Laboratory, Palo Alto, CA
#      Date            August 1999

#----------------------------------------------------------------------


sub usage {
    die "usage: iscan [-linuxdir directory] [-help] directory* OR\n" .
	"       iscan -quick [-help] directory+\n";
}

#----------------------------------------------------------------------

@libs = (
	"/skiff/local/lib/gcc-lib/arm-linux/2.95.2/",
	"/wrl/proj/itsy/kerr/ipaq/lib",
);

@apps = (
);

@linuxdirs = (
  "/wrl/proj/itsy/kerr/linuxes/ohhlinux/linux-2.4.0-test8-rmk5-np2-hh2/kernel",
  "/wrl/proj/itsy/kerr/linuxes/ohhlinux/linux-2.4.0-test10-rmk2-np3-hh1/kernel"
);

@directories = ();

$quick = 0;
while ($#ARGV >= 0) {
    $_ = shift @ARGV;
    if (/^-/) {
	if ($_ eq substr("-linuxdir", 0, length $_)) {
	    unshift(@linuxdirs, shift @ARGV);
	} elsif ($_ eq substr("-quick", 0, length $_)) {
	    $quick = 1;
	} else {
	    &usage();
	}
    } else {
	unshift(@directories, $_);
    }
}

#----------------------------------------------------------------------

sub get_sum {
    local($filename) = @_;
    open(SUM, "imageid $filename |");
    while (<SUM>) {
	if (/^\S+: ([a-fA-F0-9]+)$/) {
	    $hash = $1;
	    print "$filename $hash\n";
	    last;
	}
    }
    close(SUM);
}

if (!$quick) {
    # expand apps directories into directories
    @directories = (@directories, @apps);
    # expand libs directories into directories
    @directories = (@directories, @libs);
}

foreach $d (@directories) {
    opendir(DIR, $d) || next;
    foreach $file (readdir(DIR)) {
	get_sum("$d/$file");
    }
    closedir(DIR);
}

if (!$quick) {
    foreach $d (@linuxdirs) {
	# kernel
	opendir(DIR, $d) || next;
	foreach $file (readdir(DIR)) {
	    if ($file eq "System.map") {
		$hash = 0;
		print "$d/$file $hash\n";
	    }
	    elsif ($file eq "vmlinux") {
		$version = "";
		open(TMP, "strings $d/$file |");
		while (<TMP>) {
		    if (/^Linux version/) {
			$version = $_;
			last;
		    }
		}
		close(TMP);
		print "$d/$file $version" if ($version);
	    }
	}
	closedir(DIR);

	open(FIND, "find $d -type f -name '*.o' -print|");
	while (<FIND>) {
	    chop;
	    get_sum($_);
	}
	close(FIND);
    }
}

