#!/usr/local/bin/perl

# gpretty  version 1.0
#
# gpretty reads a "travel" file and writes a pretty formatted report.
#
# usage: gpretty [-d depth] [-M] [-h host] [-T title] [file...]
#
# -d depth   Skip items with higher depths.
#
# -M         Write menus only, ie, skip all files.
#
# -h host    Omit the indication of host for items from "host".
#
# -T title   Report title.

# TODO: change the name to travel-pretty

$0 =~ s:^.*/::;
$usage= "usage: $0 [-d depth] [-D] [-h host] [-T title] [file...]\n";

%types=("0", "",	"1", "/",	"2", "<phone>",	"3", "<ERROR>",
	"4", "<hqx>",	"5", "<pcbin>",	"6", "<uue>",	"7", "<?>",
	"8", "<tel>",	"9", "<bin>",	"R", "",	"T", "<tn3270>",
	"e", "",	"f", "<ftp>",	"h", "<html>",	"i", "<info>",
	"m", "/",	"s", "<sound>",	"w", "<?>"
       );

require "getopts.pl";

&Getopts("Md:h:T:") || die $usage;
$opt_f = "dn" unless $opt_f;

print "$opt_T\n" if $opt_T;
print "Last updated: ". `date`;
print "
Depth    Name  <Type>                                                     Host
------------------------------------------------------------------------------
";

$= = 0;  ## No page headers

while (<>) {
  ($type, $name, $path, $host, $port, $depth)= &tsplit($_);
  &write if ((!defined $opt_d) || ($depth <= $opt_d))
         && ((!defined $opt_M) || ($type eq "1") || ($type eq "7"));
}
exit 0;

sub write {
  if ($path =~ /^ftp:([^@]*)@/) {
    $xhost="ftp:$1";
    if ($path =~ m:/$:) { $xtype="/"; }
    else                { $xtype= $types{$type}; }
  }
  else {
    $xtype= $types{$type};
    $xhost= $host;
  }
  if ($opt_h) {
    $xhost="" if $host =~ /$opt_h$/io;
  }
  $xtype = "  ". $xtype unless $xtype =~ m:^/: ;

  $line = "  " x ($depth > 10 ? 10 : $depth);
  $line .= $name;
  $line = substr($line,0, 79-length($xhost)-2-length($xtype)-3);
  $line .= $xtype;
  $line .= (" " x (79-length($xhost)-2-length($line)));
  $line .= $xhost;
  printf("%2d",$depth); print $line; print "\n";
}

format =
@> @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @>>>>>>>>>>>>>>>>>>>>>>>>
$depth, ("  " x ($depth-1)).$name. $xtype, $xhost
.

sub tsplit {
  local($_)= @_;
  chop($_);
  local(@F)= split(/\t/,$_);
  if (@F == 6) {  ## gtime host port path tname depth
    return ( substr($F[4],0,1), substr($F[4],1), $F[3], $F[1], $F[2], $F[5] );
  }
  elsif (@F == 5) {  ## tname path host port depth
    return ( substr($F[0],0,1), substr($F[0],1), $F[1], $F[2], $F[3], $F[4] );
  }
  elsif (@F == 4) {  ## tname path host port
    return ( substr($F[0],0,1), substr($F[0],1), $F[1], $F[2], $F[3], undef );
  }
  else {
    warn "Malformed line: $_\n";
    return undef;
  }
}

