#!/bin/sh

if [ $# -eq 0 ] ; then
 echo "______________________________________________________________________________________________________"
 echo " Herminux file/folder packer. Usage: pack <folder or file> [output file with extension]"
 echo " (If '/' is added at end of folder, its contents are packed directly without the folder.)"
 echo " (Compression format and packer is determined from the extension of the outputfile extension.)"
 echo " (If optut-file or its extension is not given or recognized, 'tar.xz' is the default fallback method.)"
 echo " (Existing files with the same name as output-file will get overwritten automatically.)"
 echo " Recognized output-extension formats: .zip .7z  .tar  .tar.xz/.txz  .tar.bz2/.tbz/.tbz2  .tar.gz/.tgz "
 echo " These programs need to be on the system for full operation:  tar  xz  bzip2  gzip  zip  "
 echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
 exit 0

elif [ $# -gt 2 ] ; then
 echo "Too many arguments! Maybe you should double-quote the destination folder-/filename containing space."
 exit 1

else
 TARSOURCE="$1"
 if [ "${1:$((${#1}-1))}" == "/" ] ; then  #check if last character is '/' (so folder content is packed only)
  TARSOURCE=" -C ${1%/} ./ "
 fi

 if [ $# -eq 1 ] ; then
  OUTPUTFILE=${1%.*}.tar.xz   #basename is the filename without the path (but with the extension)
  echo "Packing  \"$1\"  into file  \"${OUTPUTFILE}\"  (into current folder ( \"$(pwd)\" ) "
  tar -cJvf "${OUTPUTFILE}" ${TARSOURCE}

 elif [ $# -eq 2 ] ; then  
  if [ "$(dirname "$2")" != "." ] ; then
   if [ ! -d "$(dirname "$2")" ] ; then
    echo "Creating directory: $(dirname "$2")"
    mkdir -p "$(dirname "$2")"
   fi
  fi
  FORMAT=${2##*.}  #get last part of extension e.g. "xz"

  if [ "$FORMAT" == "zip" ] ; then
   zip -r "$2" "$1"
  elif [ "$FORMAT" == "7z" ] ; then
   7za a -y "$2" "$1"
  else
   TARTYPE="-J" #init to .tar.xz by default (good compression, xz is fairly common nowadays)
   case $FORMAT in
    "tar" ) TARTYPE="" ;;   #uncompressed
    "xz" | "txz" ) TARTYPE="-J" ;;
    "gz" | "tgz" ) TARTYPE="-z" ;;
    "bz2" | "tbz" | "tbz2" ) TARTYPE="-j" ;;
      * ) echo "Unrecognized output extension! Using default xz compression..." ;;
   esac
   echo "Packing \"$1\" into file \"$2\"."
   tar ${TARTYPE} -cvf "$2" ${TARSOURCE}
  fi

 fi
 echo " "

fi

