#!/bin/sh

if [ $# -eq 0 ] ; then
 echo "______________________________________________________________________________"
 echo " Herminux unpacker command. Usage: upack <filename> [destination folder] "
 echo " (If no destination is given it will unpack to the current directory)"
 echo " (If target's directory doesn't exist it gets created automatically.)"
 echo " (Output files/folders with the same name will be overwritten without prompt.)"
 echo " Known formats: .rar .zip .xz .bz2 .gz/.gzip .Z .7z .lzma/.lz/  .tlz/.tar.lz"
 echo "   .tar .tar.xz/.txz  .tar.bz2/.tbz/.tbz2/.tb2  .tar.gz/.tgz  .tar.Z/.taz/.tz"
 echo " Corresponding binaries:  unzip, tar, xz, bzip2, gzip (decompress), lzma, 7za"
 echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
 exit 0
fi

if [ ! -f $1 ] ; then
 echo " "
 echo "Input file not found!"
 echo " "
 exit 1
fi

FORMAT=${1##*.}  #get last part of extension e.g. "xz"
FORMATLESS=${1%.*}  #get filename without the last extension
ISTAR=${FORMATLESS##*.} #it is 'tar' if we have a tar.* package

if [ $# -gt 2 ] ; then
 echo " "
 echo "Too many arguments given! If your target-folder name contains space please double-quote it."
 echo " "
 exit 1
elif [ $# -eq 2 ] ; then
 echo "Extracting files to directory \"$2\"."
 mkdir -p "$2"  #create output folder if relevant and it doesn't exist yet
else
 echo "Extracting files to current folder: \"$(pwd)\""
fi

nopath=${1##*/}
noext=${nopath%.*}

if [ "$ISTAR" == "tar" ] ; then
 if [ $# -eq 2 ] ; then tar -xvf "$1" -C "$2"  ;  else tar -xvf "$1"  ;  fi
else
 case "$FORMAT" in 
  "rar" ) if [ $# -eq 2 ]; then unrar e "$1" "$2"/  ;  else unrar e "$1"  ;  fi ;;
  "zip" | "ZIP" ) if [ $# -eq 2 ]; then unzip "$1" -d "$2" -o  ;  else unzip "$1" -o  ;  fi  ;;
  "7z"  ) if [ $# -eq 2 ]; then 7za x -y -o"$2" "$1"  ;  else 7za x -y "$1"  ;  fi  ;;
  "gz" | "gzip" | "Z" ) if [ $# -eq 2 ]; then  gzip -dcf "$1" > "$2/$noext"  ;  
                  else gzip -dcf "$1" > "$noext"  ;  fi ;;  #gunzip
  "bz2" ) if [ $# -eq 2 ]; then bzip2 -dckvf "$1" > "$2/$noext"  ;  
                           else bzip2 -dkvf "$1"  ;  fi ;; #bunzip2
  "xz"  ) if [ $# -eq 2 ]; then xz -dckvf "$1" > "$2/$noext"  ;  
                           else xz -dkvf "$1"  ;  fi ;;
  "lz" | "lzma" ) if [ $# -eq 2 ]; then lzma -dckvf "$1" > "$2/$noext"  ;  else lzma -dkvf "$1"  ;  fi ;;
  "tar" | "tgz" | "txz" | "tbz" | "tb2" | "tbz2" | "tz" | "taz" | "tlz" )  
     if [ $# -eq 2 ]; then tar -xvf "$1" -C "$2"  ;  else tar -xvf "$1"  ;  fi  ;;
 esac
fi

