#!/usr/bin/perl -w
#
# mydecode - wrapper script for uudeview / yydecode.  Accepts all of
# the same command line arguments as "uudeview".  If the script is
# given a file to decode, it checks first to see if it appears to be
# "yEnc" encoded, and if so uses the yydecode program to extract it,
# otherwise it calls uudeview with the same command line arguments
# that it was called with.
#
# This code copyright (C) 2002 by Caleb Epstein <cae at bklyn dot org>
# and released under the terms of the Perl Artistic License
# (cf. http://www.perl.com/language/misc/Artistic.html)
#
# $Id: mydecode,v 1.1 2002/03/09 16:41:27 gerard Exp $

use Cwd;
use Getopt::Std;
use Data::Dumper;

my @OLD_ARGV = @ARGV;
my %OPTIONS;

getopts ("iaocp:mzfrtdbsqne:", \%OPTIONS);

my $file = (scalar @ARGV ? $ARGV[0] : "-");
my $yenc = 0;

if (-f $file) {
   # Read through the first 200 lines of $file looking for the =ybegin
   # marker
   if (open (FILE, $file)) {
      my $line = 0;
      while (<FILE>) {
	 $yenc = 1 if /^=ybegin/;
	 last if $yenc or $line++ >= 200;
      }
      close FILE;
   } else {
      warn "Unable to open $file for reading: $!\n";
   }
}

my @CMD;

# Build yydecode command line if it is a yenc file
if ($yenc) {
   # Emulate uudeview's "-p" (output directory) for yydecode
   if (exists $OPTIONS{"p"} and -d $OPTIONS{"p"}) {
      # If user specified an output directory, we need to munge the
      # @ARGV array so that the paths are fully qualified (e.g. add
      # CWD) if they aren't already.
      my $cwd = cwd;
      @ARGV = map { ( m@^/@ or not -f ) ? $_ : "$cwd/$_" } @ARGV;
      chdir $OPTIONS{"p"};
   }
   # Call yydecode, passing all of the filenames given to us on the
   # command line
   @CMD = ("yydecode", "-l", @ARGV);
} else {
   # Just run uudeview with the original command line
   @CMD = ("uudeview");
   push (@CMD, @OLD_ARGV) if scalar @OLD_ARGV;
}

# Go!
print "# Running @CMD\n";

system (@CMD);
