: # use perl                                  -*- mode: Perl; -*-
        eval 'exec perl -S $0 "$@"'
                if $runnning_under_some_shell;
#
# Author: Petter Reinholdtsen <pere@td.org.uit.no>
# Date:   1999-05-25
#
# Compare linked up Store app versions between two linktrees.  Use it to see
# which applications differ between linktree levels (ie. newer vs normal)
#
# Usage: $0 <host1> <host2> ...

use strict;

package main;

my $rsh = $ENV{RSH} || "ssh -n -x";
my $treeinfo = "/store/etc/linktree.info";

my @hosts = @ARGV;
my ($host, @apps, @listapp, @versions, %appver, %hostapp);

for $host (@hosts) {
  open(RSH, "$rsh $host cat $treeinfo 2> /dev/null |") || warn "Unable to log into $host";
  while (<RSH>) {
    chomp;
    next if /^\#/;
    next unless /linkedup/;
    my($app, $version) = /^(\S+) linkedup \S+ (\S+) /;
    add_host_app($host, $app, $version);
  }
  close(RSH);
}

&find_diff();
&list_app_diff();

sub add_host_app # host, app, version
  {
    my ($host, $app, $version) = @_;
    push(@apps, $app) unless grep($_ eq "$app", @apps);
    push(@versions, $version) unless grep(/$version/, @versions);

    if ( !defined $appver{$app} ) {
      $appver{$app} = $version;
    }

    $hostapp{"$host:$app"} = $version;
  }

sub find_diff
  {
    my ($app, $host, $list);
    foreach $app (@apps) {
      my $ver = $appver{$app};
      $list = 0;
      foreach $host (@hosts) {
	$list = 1 if ( !defined $hostapp{"$host:$app"}
		       || $ver ne $hostapp{"$host:$app"} );
      }
      push(@listapp, $app) if $list;
    }
  }

sub list_app_diff
  {
    if (scalar @listapp) {
      my $applen = longest_string(@listapp);
      my $verlen = longest_string(@versions, @hosts);
      my $host;
      printf "%-${applen}s ", "Application";
      for $host (@hosts) {
	printf "%-${verlen}s ", $host;
      }
      print "\n\n";
      my $app;
      for $app (sort @listapp) {
	printf "%-${applen}s ", $app;
	for $host (@hosts) {
	  if (defined $hostapp{"$host:$app"}) {
	    printf "%-${verlen}s ", $hostapp{"$host:$app"};
	  } else {
	    printf "%-${verlen}s ", "-";
	  }
	}
	print "\n";
	  
      }
    }
  }

sub longest_string # @strings
  {
    my $max = 0;
    my ($str, $len);
    foreach $str (@_) {
      $len = length($str);
      $max = ($max < $len) ? $len : $max;
    }
    return $max;
  }
