#!/bin/sh
# - belongs to /opt/scripts/bin
# - needs: tar, bzip2, gzip, bzcat, zcat, test, sh, md5sum, exit
# - should work on every unix!
# - version: 0.6
#
# what is it:
# ct   => create normal
# ut   => unpack normal    (with optional md5 check)
# ctv  => create verbose
# utv  => unpack verbose   (with optional md5 check)
# utt  => unpack with test (without giving tar.gz or tar.bz2)

# samples:
# ct gz dir  ->  dir.tar.gz
# ct bz2 dir ->  dir.tar.bz2
# dwp name   ->  makes an darkwood package (dwp) of current directory
# ut archiv.tar.bz2
# ut archiv.tar.gz
# utt archiv -> tests archiv.tar.bz2 archiv.tar.gz -> unpack first found archive

function error() {
 echo -en "\007"
 exit 1
}

function utt_found() {
 ut $1
 F="lala"
}

function md5_check() {
 test -r $1.md5 || return
 md5_tar=`md5sum $1  | cut -d' ' -f1`
 md5_md5=`cat $1.md5 | cut -d' ' -f1`
 if [ "$md5_tar" == "$md5_md5" ]; then
  md5_okay="(md5 checksum okay)"
  return
 fi
 echo " -> md5 checksum of $1 isn't correct!"
 exit 2
}

B=`basename $0`
test "x$B" = "x" && error
test "x$1" = "x" && error

v=""
test "x$B" = "xutv" && v="-v"
test "x$B" = "xctv" && v="-v"

if [ "$B" == "ut" -o "$B" == "utv" ]; then 
 for i in $*; do
  test -r $i || continue
  G=`echo $i | grep -E 'gz$'`
  [ "x$G" != "x" ] && CAT="zcat"
  G=`echo $i | grep -E 'bz2$'`
  [ "x$G" != "x" ] && CAT="bzcat"
  md5_okay=""
  md5_check $i
  echo " -> $CAT $i | tar $v -x $md5_okay"
  $CAT $i | tar $v -x
 done
 exit 0
fi

if [ "$B" == "ct" -o "$B" == "ctv" ]; then
 test "$1" = "gz"  && PIPE="gzip -9"
 test "$1" = "bz2" && PIPE="bzip2 -9"
 test "x$PIPE" = "x"  && error
 E=$1 && shift
 for i in $*; do
  if [ ! -d $i ]; then
   echo " -> directory $i not found!"
   continue
  fi
  echo " -> tar $v -c $i | $PIPE > $i.tar.$E"
  tar $v -c $i | $PIPE > $i.tar.$E
  md5sum $i.tar.$E > $i.tar.$E.md5
 done
 exit 0
fi

if [ "$B" == "dwp" ]; then
 echo " -> tar -c * | bzip2 -9 > $1.dwp"
 tar -c * | bzip2 -9 > $1.dwp
 md5sum $1.dwp > $1.dwp.md5
fi


if [ "$B" == "utt" ]; then
 for i in $*; do
  F=""
  test "x$F" == "x" && echo " -> trying $i.tar.bz2"
  test "x$F" == "x" && test -r $i.tar.bz2 && utt_found $i.tar.bz2
  test "x$F" == "x" && echo " -> trying $i.tar.gz"
  test "x$F" == "x" && test -r $i.tar.gz && utt_found $i.tar.gz
  test "x$F" == "x" && echo " -> trying $i.tgz"
  test "x$F" == "x" && test -r $i.tgz && utt_found $i.tgz
  test "x$F" == "x" && echo " -> no archiv for $i found!"
 done
 exit 1
fi

error
