#!/usr/bin/perl 

=head1 NAME

capmin.pl - termcap minimizer

=head1 SYNOPSYS

capmin.pl [-h] [-f <termcap> ] <terminal>...

=head1 DESCRIPTION

This program produce minimal variant of termcap with only terminal
entries specifed in command line. This is usefull for small
installations where filesystem size is limited. Automatically handle
tc capabilities. Result is sent to stdout.

The options are:

=over 3

=item -f <termcap>

Set termcap file name. Default is /etc/termcap.

=item -h

Print usage information and exit.

=back

=head1 BUGS

Doesn't work on mutually recursive terminal entries, ie.:

term0:tc=term1:
term1:tc=term0:

But this is not allowed in termcap. (?)

=head1 SEE ALSO

L<termcap(5)>

=head1 LICENSE

This program is distributed under the terms of GNU General Public
License as published by the Free Software Foundation.

=head1 AUTHOR

Arkadi E. Shishlov [arkadi at it.lv]

=cut

#use Data::Dumper;
use Getopt::Long;

sub usage {
    print <<EOU
Usage: capmin.pl [-h] [-f <termcap> ] <terminal>...
    -h           print this message
    -f <termcap> specify alternate termcap file name
                 default is /etc/termcap
EOU
    ;exit(1);
}

    usage() unless GetOptions(\%opt, ('h', 'f=s'));
    usage() if $opt{'h'} || !@ARGV;

    $termcap = $opt{'f'} || "/etc/termcap";
    open(T, "< $termcap") || die "cannot open $termcap";

    undef $/;
    $_ = <T>;
    
    s/^#.*//mg;
    s/^\n//mg;
    
    @t = split /:\n/;
    
    $len = @t;

    for($i = 0; $i < $len; ++$i) {
        $t[$i] =~ m/([^:]+)/;
        map { $n{$_} = $i if $_ !~ /\s/ } split(/\|/, $1);
    }
    #print Dumper(\%n); exit(0);

    sub addTerm {
        my $r = shift;
        my $i = $n{$r};
        if(!$i) { print STDERR "no such terminal: $r\n"; return; }
        my $d = $t[$i] .":";
        $ot{$i} = 1;
        #print "# $r = \n$d\n";
        while($d =~ /:tc=([^:]+)/g) {
            #print "# $r depend on $1\n";
            addTerm($1);
        }
    }
    map { addTerm($_) } @ARGV;
    map { print "$t[$_]:\n"; } keys %ot;

