#!/usr/bin/perl -w

# show sorted content of 7z archive with date+time, size and file name
# surpress superflous information and ignores password prompt

$0 =~ s:.*/::;

$usage = "usage: $0 file.7z\n";
die $usage if scalar(@ARGV) != 1 or "@ARGV" =~ /^-/;

$file = shift @ARGV;

die "$0: \"$file\" does not exist\n"        unless -e $file;
die "$0: \"$file\" is not a regular file\n" unless -f $file;
die "$0: \"$file\" is not readable\n"       unless -r $file;

open $list,'-|',qw'7za l -px',$file or exit $?;

# default table columns and lengths
$r1s = 20;
$r1l = 6;
$r2s = 39;
$r2l = 14;

while (<$list>) {
  die "$1\n" if /(Error:.*)Wrong password/;
  if (/^( +Date.*)( Attr )( +Size )( +Compressed +)(Name)/) {
    $r1s = length($1);
    $r1l = length($2);
    $r2s = length($1)+length($2)+length($3);
    $r2l = length($4);
    &reduce;
    print;
    last;
  }
}

$_ = <$list>;
&reduce;
print;

while (<$list>) {
  s:$:/: if substr($_,$r1s,1) eq 'D';
  $file = substr($_,$r2s+$r2l,999);
  &reduce;
  if (/^---/) {
    $tail = $_;
    last;
  }
  $list{$file} = $_;
}

if (defined($_ = <$list>)) {
  &reduce;
  $tail .= $_;
}

foreach $file (sort keys %list) {
  print $list{$file};
}

print $tail;

sub reduce {
  substr($_,$r2s,$r2l) = ''; # delete Compressed column
  substr($_,$r1s,$r1l) = ''; # delete Attr column
}
