#! /usr/bin/perl -w

my $sshFile = '/etc/ssh/ssh_config';
open SSH,"<$sshFile" or die "could not read $sshFile: $!\n";
my @contents = <SSH>;
close SSH;

chomp @contents;

sub getNextBlock {
   my $currentLine = shift;
   my $name = '';
   my $target = '';
   my $user = '';
   my $port = '';
   while ( $currentLine < @contents ) {
#      print "$currentLine\t$contents[$currentLine]\n";
      if ( $contents[$currentLine] =~ m/^\s*$/ ) { # blank line, skip it
         $currentLine++;
         next;
      }
      my ($key,$value) = split( /\s+/, $contents[$currentLine] );
      if ( lc( $key ) eq 'host' ) {
         return ($currentLine, join( "\t", ($name,$target,$user,$port) ) ) if $name;
         $name = $value;
      } elsif ( lc( $key ) eq 'hostname' ) {
         $target = $value;
      } elsif ( lc( $key ) eq 'user' ) {
         $user = $value;
      } elsif ( lc( $key ) eq 'port' ) {    
         $port = $value;
      }
      $currentLine++;
    }
    return ( $currentLine, '' );
}

sub skipHeader {
   my $toFind = '#      System Wide Aliases for all users';
   $currentLine = 0;
   while ( $currentLine < @contents && $contents[$currentLine] !~ m/$toFind/ ) {
      $currentLine++;
   }
   return $currentLine;
}


my $line = &skipHeader();
my @info;
while ( $line < @contents ) {
   my $targets;
   ( $line, $targets ) = &getNextBlock( $line );
#   print "$line\t$targets\n";
   push @info, $targets;    
}
print "NumEntries = " . scalar( @info ) . "\n";
print "Host\tTarget\tUser\tPort\n" . join( "\n", @info ) . "\n";
1;
