#!/usr/bin/perl

# to think this used to be just:
# perl -MMIME::Base64 -ne 'chomp;push (@doc,$_);END{print MIME::Base64::decode(join '', @doc)}' < somefile > anotherfile

# begin main
{
  use MIME::Base64;
  use Getopt::Long;
  GetOptions (
    "help" => \$opt_Help,
    "infile:s" => \$opt_Infile,
    "outfile:s" => \$opt_Outfile,
  );

  # no help and exit
  if (defined($opt_Help))
  {
    print "\nusage for $0 (low budget base64 decoder):\n\n";
    print "\tThere is no help for you, you ninny!\n\n";
    print "\t--help\t\tWhat ur lookin' at!\n\n";
    print "\t--infile\tfile to decode\n";
    print "\t--outfile\twhere to put the output\n\n";
    print "\tYou can also use redirection, but it won't protect you against clobbering.\n\n";
    print "\tNote that this program accepts base64 blobs only. You have to strip off MIME\n";
    print "\tgarbage to get it to work correctly. This program is for helping when the MIME\n";
    print "\tgot screwed up, but you think you can still salvage the base64 blobs.\n\n";
    exit 1;
  }

  # open infile or open stdin
  if (defined($opt_Infile))
  {
    print "found inf\n";
    open($fh, "<$opt_Infile") || die "Can't open file for input: $opt_Infile. Error $!";
  }
  else
  {
    open($fh, "-");
  }

  # get data until we hit eof
  while(<$fh>)
  {
    chomp;
    push (@doc, $_);
  }

  # close the file handle
  if (defined($opt_Infile))
  {
    close($fh) || die "Can't close file for input: $infile. Error $!";
  }

  
  # decode the base64 blob
  $decoded = MIME::Base64::decode(join('', @doc));

  # write out the decoded base64 blob
  if (defined($opt_Outfile))
  {
    if ( ! -f $opt_Outfile )
    {
      open(OUTF, ">$opt_Outfile") || die "Can't open file for output: $opt_Outfile. Error $!";
    }
    else
    {
      print "refusing to clobber already existing file: $opt_Outfile. Exiting.\n";
      exit 1;
    }
    print OUTF $decoded;
    close(OUTF) || die "Can't close file for output: $opt_Outfile. Error $!";
  }
  else
  {
    print $decoded;
  }

}
# end main
