#!/usr/local/bin/perl

### very preliminary version, just enough to get it working
### still missing: check proper version of tar, cpio, gzip
### needs much cleaning                     WF Feb 20, 2001

$|=1;
open IN, "lesspipe.sh.in";
open OUT, ">lesspipe.sh";
$in = 1;
while (<IN>) {
  if ( /^#ifdef\s+(.*)/ ) {
    %rep = ();
    $_ = $1;
    chomp;
    @progs = split /,/;
    $in = inpath (@progs);
  } elsif (/^#endif\s/ ) {
    %rep = ();
    $in = 1;
  } else {
    for $p (keys %rep) {
      s/\b$p\b/$rep{$p}/ unless /^#/;
    }
    print OUT if $in;
  }
}

sub inpath {
  for my $prog ( @_ ) {
    return 1 if $have{$prog} and $have{$prog} !~ /^n/i;
    return 0 if $have{$prog} and $have{$prog} =~ /^n/i;
    my $ok = 0;
    my $failed = 0;
    print "checking $prog ... ";
elem: for ( split /:/, $ENV{PATH} ) {
      next unless m|^/|; # consider only absolute PATH elements
      if ( -x "$_/$prog" ) {
# special treatment for file program
	if ( $prog eq 'file') {
	  my $rc = system "$_/$prog -L ./configure >/dev/null 2>&1";
	  $failed = 1 if $rc;
	  next elem if $rc;
	  $rep{$prog} = "$_/$prog" if $failed;
	}
	print "yes\n";
	$ok = 1;
	$have{$prog} = "$_/$prog";
	last elem;
      }
    }
    my $yesno = get_answer($prog) unless $ok;
    $have{$prog} = $yesno unless $ok;
    return 0 if ! $ok and $yesno !~ /^y/i;
  }
  return 1;
}

sub get_answer {
  my $prog = shift;
  my $yesno;
  while ( $yesno !~ /^[yn]/i ) {
    print "Include code anyway [y/N or <full_path_to_$prog>] ? ";
    $yesno = <STDIN>;
    chomp $yesno;
    if ( $yesno =~ m|^/| ) {
      if ( -x $yesno ) {
	$rep{$prog} = $yesno;
	$yesno = 'y';
# special treatment for file program
	if ( $prog eq 'file') {
	  my $rc = system "$_/$prog -L ./configure >/dev/null 2>&1";
	  if ( $rc ) {
	    $yesno = '';
	    delete $rep{$prog};
            print "Program $prog not useable, option -L not working\n";
	  }
	}
      } else {
	print "Program $prog not found (or at least not executable)\n";
	$yesno = '';
      }
    }
  }
  return $yesno;
} 
