#! /usr/bin/perl

# Maintained by Eduard Bloch <edi@ka.linux.de>
# http://www.eduard.bloch.com/edecosi/unp.en.html
#
# Originaly written by Andr Karwath, 1997
# andre.karwath@informatik.tu-chemnitz.de
# http://www.aka-online.de
#
# "unp" runs the correct unpack program depending on the file extension
# of the given parameter.
# 
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# -----------------------------------------------------------------------
# If you make changes to this script, please feel free to forward the new 
# version to eduard@bloch.com or Andre.Karwath@informatik.tu-chemnitz.de
# -----------------------------------------------------------------------
# You need some archiver and compressor programs for extracting:
# GNU tar, gzip, bzip2, ar, rpm, unrar or rar, unarj, unzip and lha


$not_found=": not found\n";
$not_read=": not readable\n";
$unsup=": unsupported format\n";
$formats="
tar[.gz,.bz2], gz, bz2, Z, ar/deb, rpm, shar, rar, arj, zip, LHa, cab, ace,
tnef, uu (mail, news), mime, hqx, sea, zoo, pmd, cpio, afio, lzop
";
$usage="
usage: unp file [file]...
file: compressed file(s) to expand

Use -- to pass arguments to external programs, eg. some tar options:
unp fastgl.tgz xmnt.tgz -- -C /tmp

Special option:
  -f  Continue even if program availability checks fail
  -u  For Debian packages:
      - extract data.tar.gz after each operation
      - extract control.tar.gz in control/<filename>/
      For other archives:
      - create directory <filename without suffix>/
      - extract contents there

currently supported extensions and formats are".$formats;
$tryfile=" - unknown extension, checking with \"file\"\n";
$testbz2=" contains bzip2-compressed data, determining data type...\n";
$testgz=" contains gzip-compressed data, determining data type...\n";
$testlz=" contains lzop-compressed data, determining data type...\n";
$skip=" exists allready, skipping...\n";
$is_dir=" is a directory, skipping...\n";
$nopack="Warning, the following unarchiv program(s) could not be found:
  ";
$plzinst="Please install the package(s): ";
$or="or";

# localisation part (only german at the moment):
if($ENV{'LANG'}=~ "^de" || $ENV{'LC_MESSAGES'}=~ "^de"  ){
$not_found=" wurde nicht gefunden!\n";
$not_read=" konnte nicht gelesen werden!\n";
$unsup=": dieses Format wird nicht unterstuetzt!\n";
$usage="
Aufruf: unp Datei [Datei] ...
Datei: eine oder mehrere komprimierte Datei(en) zum entpacken

Optionen:
  -f  Weitermachen, auch wenn Checks der Entpacker-Verfgbarkeit fehlschlagen
  -u  Fuer Debian-Pakete:
      - Nach jeder Operation data.tar.gz entpacken
      - control.tar.gz nach control/<Achiv-Name>/
      Fuer andere Archive:
      - Verzeichniss <Archivename ohne Endung>/ erstellen
      - Archiv dort entpacken

Optionen nach -- werden an externe Programme uebergeben, z.B. tar-Optionen:
unp fastgl.tgz xmnt.tgz -- -C /tmp

Derzeit unterstuetzte Erweiterungen und Formate:".$formats;
$tryfile=" - Endung unbekannt, ueberpruefe mit \"file\"...
";
$testbz2=" enthlt bzip2-komprimierte Daten, ueberpruefe den Datentyp...\n";
$testgz=" enthlt gzip-komprimierte Daten, ueberpruefe den Datentyp...\n";
$testlz=" enthlt lzop-komprimierte Daten, ueberpruefe den Datentyp...\n";
$skip=" existiert bereits, ueberspringe...\n";
$is_dir=" ist ein Verzeichnis\n";
$nopack="Warnung, folgende(s) Entpacker-Programm(e) wurde(n) nicht gefunden:
  ";
$plzinst="Bitte installieren Sie folgend(e) Paket(e): ";
$or="oder";
}

%pkgmap = (
   cpio, "afio $or cpio",
   afio, "afio $or cpio",
   rpm2cpio, "rpm, afio $or cpio",
   unshar, sharutils,
   uudecode, sharutils,
   PPMd, ppmd,
   rar, "rar or unrar",
   ar, binutils,
   unarj, "unarj or arj", 
   hexbin, macutils,
   macunpack, macunpack,
   gunzip, gzip,
   bunzip2, bzip2,
   formail, "formail, mpack"
);

&print_usage if ($#ARGV<0 || $ARGV[0] eq "-h");

my $command;
my $force;

sub set_command {

   my %cand;
   my $lastcmd;
   for $cmd (@_) {
      $cmd =~ /^(\S+)(\s|$)/;
      my $prog=$1;
      # HACKS
      set_command("mpack") if($prog eq "formail");
      set_command("cpio ") if($prog eq "cpio");
      for(split(/:/,$ENV{"PATH"})) {
         if(-x "$_/$prog") {
            $command=$cmd;
            return;
         }
         $lastcmd=$cmd;
         $cand{$prog}=$prog;
      }
   }
   # override with custom package names where needed
   for(keys %cand) { $cand{$_}=$pkgmap{$_} if( defined($pkgmap{$_}) ); }
   print "$nopack ".join(" $or ", keys %cand)."\n$plzinst".join(" $or ", values %cand)."\n";
   $command=$lastcmd;
   $force || exit 1;
}
   
sub testfile {
   print $file.$tryfile;
   $filestr=`file \"$file\"`;
   if ($filestr =~ /(gzip)/gi){
      print $file.$testgz;
      $file=~/([^\/]*)$/i; $target="$1.unp";
      if (-f $target){ print $target.$skip; next LOOP;} # mgl. fall:.unp existiert, ist aber doch ein tar.gz! -> nachher fixen
      $command=(`zcat \"$file\" | file -`=~/tar/i) ? "zcat \"$file\" | tar -xvf - $ARGS" : "zcat < \"$file\" > $target";
   };
   if ($filestr =~ /(bzip2)/gi){
      print $file.$testbz2; 
      $file=~/([^\/]*)$/i; $target="$1.unp";
      if (-f $target){ print $target.$skip; next LOOP;}
      $command=(`bzcat \"$file\" | file -`=~/tar/i) ? "bzcat \"$file\" | tar -xvf - $ARGS" : "bzcat < \"$file\" > $target";
   };
#   if ($filestr =~ /(lzop)/gi){
#      print $file.$testlz;
#      $file=~/([^\/]*)$/i; $target="$1.unp";
#     if (-f $target){ print $target.$skip; next LOOP;} # mgl. fall:.unp existiert, ist aber doch ein tar.lz! -> nachher fixen
#      $command=(`lzop -d < \"$file\" | file -`=~/tar/i) ? "lzop -d < \"$file\" | tar -xvf - $ARGS" : "echo Decompressing $target ; lzop -d < \"$file\" > $target";
#   };
   # lzop does manage multipart archives and name collisions. lzoped tar
   # archives are not supported directly, but I don't care now
   if ($filestr =~ /lzop/i) { set_command "lzop -d $ARGS \"$file\""; }
   
   if ($filestr =~ /RAR.*archive/i) { set_command("rar x $ARGS \"$file\"","unrar x $ARGS \"$file\""); }
   if ($filestr =~ /tar.*archive/i) { set_command "tar -xvf \"$file\" $ARGS"; }
   if ($filestr =~ /(Debian binary package|\ ar.*archive)/i) { set_command "ar xv \"$file\" $ARGS"; }
   if ($filestr =~ /LHa.*archive/i) { set_command "lha x $ARGS \"$file\""; }
   if ($filestr =~ /ARJ.*archive/i) { set_command("unarj x \"$file\"","arj x \"$file\" "); }
   if ($filestr =~ /CAB file/i) { set_command "cabextract \"$file\""; }
   if ($filestr =~ /cpio/i) { set_command("afio -Z -v -i \"$file\"","cpio -i -d	--verbose  $ARGS < \"$file\""); }
   if ($filestr =~ /Zip.*archive/i) { set_command "unzip $ARGS \"$file\""; }
   if ($filestr =~ /Zoo.*archive/i) { set_command "unzoo -x $ARGS \"$file\""; }
   if ($filestr =~ /shell.*archive/i) { set_command "unshar $ARGS \"$file\""; }
   if ($filestr =~ /Transport Neutral Encapsulation Format/i) { set_command "tnef -v $ARGS \"$file\""; }
   if ($filestr =~ /uuencoded/i) { set_command "uudecode $ARGS \"$file\""; }
   if ($filestr =~ /(mail text)|news/i) { set_command "formail -s munpack < \"$file\""; }
   if ($filestr =~ /RPM/) { set_command "rpm2cpio < \"$file\" | cpio -i -d	--verbose $ARGS";}
   # RAR can also create executables
   if ($filestr =~ /executable/i){set_command "orange \"$file\" || unzip \"$file\" || unrar x \"$file\" || rar x \"$file\" || unarj x \"$file\" || lha x \"$file\"";}
   if ($filestr =~ /BinHex/i) {set_command "a=`hexbin -v \"$file\" 2>&1`; bla=`echo \$a | sed -e 's/.* name=\"\\(.*\\)\".*/\\1/'`; macunpack -v \$bla.bin;"}

   # if still nothing could be found, print an error message
   if ($command eq "") {
      print $file.$unsup;
      next LOOP;
   }
}

arglabel: foreach $arg (@ARGV){
	if("$arg" eq "-u"){$dataunp=1 ; next arglabel};
	if("$arg" eq "-f"){$force=1 ; next arglabel};
	if("$arg" eq "--"){$argvalue=1; next arglabel};
	if($argvalue){
		$ARGS.=" $arg";
	}else{
		push(@FILES,$arg);
	}
}

LOOP: foreach $file (@FILES) {
  if (!-e $file) {
     print $file.$not_found;
     if ($file == "-") 
       {$stdin=1}
     else
       {next LOOP;}
  }

  if ((!-r $file) && (!$stdin)) {
     print $file.$not_read;
     next LOOP;
  }
  
	if (-d $file) {
     print $file.$is_dir;
     next LOOP;
  }
	undef $command;

  # not just gunzip, create new file with uncompressed data in the current
	# directory, same for bz2
	if ($file =~ /([^\/]*)\.(gz|Z)$/i) {if (-f $1){ print $1.$skip; next LOOP;};
			set_command "gunzip < \"$file\" > $1"; }
  if ($file =~ /([^\/]*)\.(bz2$)/i) {if (-f $1){ print $1.$skip; next LOOP;};
			set_command "bunzip2 < \"$file\" > $1"; }
	if ($file =~ /([^\/]*)\.lzo$/i) {if (-f $1){ print $1.$skip; next LOOP;};
			set_command "lzop -v -d \"$file\""; }
	
	# check also for _tar, because of broken filenames
  if ($file =~ /(\.|_)tar$/i) { set_command "tar -xvf \"$file\" $ARGS"; }
	if ($file =~ /(\.|_)rpm$/i) { set_command "rpm2cpio < \"$file\" | cpio -i -d	--verbose $ARGS";}
	if ($file =~ /(\.|_)tar\.gz$/i) { set_command "tar -xvzf \"$file\" $ARGS"; }
  if ($file =~ /(\.|_)tar\.bz2$/i) { set_command "bunzip2 -c \"$file\" | tar -xvf - $ARGS"; }
	
	if ($file =~ /\.tgz$/i) { set_command "tar -xvzf \"$file\" $ARGS"; }
	if ($file =~ /\.(tzo|tar\.lzop)$/i) { set_command "lzop -v -d \"$file\" | tar -xv $ARGS"; }
  if ($file =~ /\.rar$/i) { set_command("rar x \"$file\" $ARGS","unrar x \"$file\" $ARGS"); }
  if ($file =~ /\.(ar|deb)$/i) { set_command "ar xv \"$file\" $ARGS"; }
  if ($file =~ /\.l(ha|zh)$/i) { set_command "lha x $ARGS \"$file\""; }
  if ($file =~ /\.arj$/i) { set_command ("arj x \"$file\"","unarj x \"$file\""); }
  if ($file =~ /\.zip$/i) { set_command "unzip $ARGS \"$file\""; }
  if ($file =~ /\.zoo$/i) { set_command "unzoo -x $ARGS \"$file\""; }
  if ($file =~ /\.cab$/i) { set_command "cabextract \"$file\""; }
  if ($file =~ /\.ace$/i) { set_command "unace e $ARGS \"$file\""; }
  if ($file =~ /\.dat$/i) { set_command "tnef -v $ARGS \"$file\""; }
  if ($file =~ /\.pmd$/i) { set_command "PPMd x $ARGS \"$file\""; }
  if ($file =~ /\.(sea|sea\.bin)$/i) { set_command "macutils -v $ARGS \"$file\""; }
  if ($file =~ /\.uu$/i) { set_command "uudecode $ARGS \"$file\""; }
	
	# assume that exe is just an arcive with executable header and try
	# some programs
	if ($file =~ /\.exe$/i) { set_command "orange \"$file\" || unzip \"$file\" || unrar x \"$file\" || rar x \"$file\" || unarj x \"$file\" || lha x \"$file\"";}

  if ($command eq "") {testfile};
	if ($dataunp){
#print "binda\n$command\n$1";
	  if($file =~ /([^\/]*)\.deb$/i) {
      &doit;
      system ("tar zxvf data.tar.gz; mkdir -p control/$1; cd control/$1; tar zxvf ../../control.tar.gz");
    }
   else {
      # Wo sind wir gerade? (Achtung newline muss weg!!)
      chomp($pwd = `pwd`);
      # Pfad fixen
      $0 =~ s!^./!$pwd/!;
      $file =~ /([^\/]+)\.(\w)+$/i;
      $newdir=$1;
      if($file !~ m/^\//) { # wenn der pfad nicht absolut ist
        $file = "$pwd/$file";
      }
      mkdir $newdir;
      chdir $newdir;
      system ($0, $file);
      chdir $pwd;
   }
	}
  else {
    &doit;
  }
}

sub doit {
   #print "binda\n$command\n$1";
  if(system ($command)) {
  # if execution failed, try file
    testfile;
  };
}

# -----------------------------------------------------------------------------
sub print_usage {
  print $usage;
	die "\n";
}
# -----------------------------------------------------------------------------
