#!/bin/sh

# ------------------------
# unpack-them.sh
# version 1.7.5.4
# ------------------------

is_supported_archive()
# parameters: < archive name >
{
  if [ $# -eq 1 ]; then
    f_name=$1
    [ -f "${f_name}" ] || return 1
    type_of_file=`file "${f_name}" | cut -d':' -f2`
    is_bzip2=`echo "${type_of_file}" | grep "bzip2 compressed data"`
    is_xz=`echo "${type_of_file}" | grep "XZ compressed data"`
    is_gzip=`echo "${type_of_file}" | grep "gzip compressed data"`
    is_tar=`echo "${type_of_file}" | grep "tar archive"`
    [ -z "${is_bzip2}" ] && [ -z "${is_xz}" ] && [ -z "${is_gzip}" ] && [ -z "${is_tar}" ] && return 1
    return 0
  else
    return 1
  fi
}

unpack_if_archive()
# parameters: < archive name > [ number ]
{
  if [ $# -lt 1 ]; then
    echo "bad parameters for unpack_if_archive()"
  fi
  
  f_name=$1
  the_n=$2
  
  if [ -f "${f_name}" ]; then
    type_of_file=`file "${f_name}" | cut -d':' -f2`
    is_bzip2=`echo "${type_of_file}" | grep "bzip2 compressed data"`
    is_xz=`echo "${type_of_file}" | grep "XZ compressed data"`
    is_gzip=`echo "${type_of_file}" | grep "gzip compressed data"`
    is_tar=`echo "${type_of_file}" | grep "tar archive"`
    if [ ! -z "${is_bzip2}" ]; then
      [ -z "${the_n}" ] || printf "[#%.4d] " $the_n
      printf "%s: %s" "extracting bzip2 archive" "${f_name}..."
      tar xjf "${f_name}" 1>/dev/null
      [ $? -eq 0 ] && echo " done"
    elif [ ! -z "${is_xz}" ]; then
      [ -z "${the_n}" ] || printf "[#%.4d] " $the_n
      printf "%s: %s" "extracting xz archive" "${f_name}..."
      unxz "${f_name}"
      f_name=`echo "${f_name}" | sed 's/\.xz//'`
      tar xf "${f_name}" 1>/dev/null
      ##tar xJf "${f_name}" 1>/dev/null
      [ $? -eq 0 ] && echo " done"
    elif [ ! -z "${is_gzip}" ]; then
      [ -z "${the_n}" ] || printf "[#%.4d] " $the_n
      printf "%s: %s" "extracting gzip archive" "${f_name}..."
      tar xzf	"${f_name}" 1>/dev/null
      [ $? -eq 0 ] && echo " done"
    elif [ ! -z "${is_tar}" ]; then
      [ -z "${the_n}" ] || printf "[#%.4d] " $the_n
      printf "%s: %s" "extracting tar archive" "${f_name}..."
      tar xf "${f_name}" 1>/dev/null
      [ $? -eq 0 ] && echo " done"
    fi
  fi
}

# check for required binaries
REQD_BINS=""
which tar >/dev/null 2>&1 || type tar >/dev/null 2>&1 || REQD_BINS="tar,${REQD_BINS}"
which file >/dev/null 2>&1 || type file >/dev/null 2>&1 || REQD_BINS="file,${REQD_BINS}"
which grep >/dev/null 2>&1 || type grep >/dev/null 2>&1 || REQD_BINS="grep,${REQD_BINS}"
if [ ! -z "${REQD_BINS}" ]; then
  echo -e `basename ${0}`: "Required binaries (${REQD_BINS}\010) are not present."
  exit 1
fi

list_of_files=`ls ./`
archive_num=0
for the_file in `echo "${list_of_files}"`; do
  is_supported_archive "${the_file}" && archive_num=`expr $archive_num '+' 1` && \
    unpack_if_archive "${the_file}" $archive_num
done
