#!/bin/sh

#convert a .tar.gz file to .pet...
#passed param is file to be converted.
#this works for md5sum returning 8-bit characters!
# 131122 add support for tar.xz

sync
TARBALL=$1
#chmod +w $TARBALL #make it writable.
chmod 644 $TARBALL #make it writable.

#only accept .tgz or .tar.gz files...
#add txz and tar.xz
EXT=''
echo -n "$TARBALL" | grep -q '\.tar\.gz$' && EXT='.tar.gz'
echo -n "$TARBALL" | grep -q '\.tgz$' && EXT='.tgz'
echo -n "$TARBALL" | grep -q '\.tar\.xz$' && EXT='.tar.xz'
echo -n "$TARBALL" | grep -q '\.txz$' && EXT='.txz'
[ "$EXT" ] || exit 1

#split TARBALL path/filename into components...
BASEPKG="`basename $TARBALL $EXT`"
DIRPKG="`dirname $TARBALL`"
[ "$DIRPKG" = "/" ] && DIRPKG=""

case $EXT in
*gz)OPT=-z;;
*xz)OPT=-J;;
esac

case $EXT in
*tgz)mv -f $TARBALL $DIRPKG/${BASEPKG}.tar.gz
 TARBALL="$DIRPKG/${BASEPKG}.tar.gz"
 EXT='.tar.gz';;
*txz)mv -f $TARBALL $DIRPKG/${BASEPKG}.tar.xz
 TARBALL="$DIRPKG/${BASEPKG}.tar.xz"
 EXT='.tar.xz';;
esac

#exit
#if tarball expands direct to '/' want to wrap around it (slackware pkg)... 100628 add -z ...
#man bad bug here... the thing isn't expanded! #131122
if [ "`tar ${OPT} --list -f $TARBALL | head -n 1`" = "./" ];then
# [ -d $DIRPKG/$BASEPKG ] && rm -rf $DIRPKG/$BASEPKG #a bit radical 
 [ -d $DIRPKG/$BASEPKG ] && exit 1
 mkdir $DIRPKG/$BASEPKG
 mv $TARBALL $DIRPKG/$BASEPKG/
 (cd $DIRPKG/$BASEPKG/;tar xf $TARBALL;rm $TARBALL)
 #rm $DIRPKG/$BASEPKG/${BASEPKG}${EXT}
 #can put other files in here if want...
 
 tar --remove-files -c -f $DIRPKG/${BASEPKG}.tar $DIRPKG/$BASEPKG/
 case $EXT in
 *gz)gzip --best $DIRPKG/${BASEPKG}.tar ;;
 *xz)xz -z $DIRPKG/${BASEPKG}.tar ;;
 esac
 #[ -d $DIRPKG/$BASEPKG ] && rmdir $DIRPKG/$BASEPKG
fi

FULLSIZE="`stat --format=%s ${TARBALL}`"
MD5SUM="`md5sum $TARBALL | cut -f 1 -d ' '`"
echo -n "$MD5SUM" >> $TARBALL
sync
#NEWNAME="`echo -n "${TARBALL}" | sed -e 's/\\.tar\\.gz$/\\.pet/g'`"
#mv -f $TARBALL $NEWNAME
mv -f $TARBALL $DIRPKG/${BASEPKG}.pet
sync

###END###
