#!/bin/sh

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

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

#only accept .tgz or .tar.gz files...
EXT=''
[ ! "`echo -n "$TARBALL" | grep '\\.tar\\.gz$'`" = "" ] && EXT='.tar.gz'
[ ! "`echo -n "$TARBALL" | grep '\\.tgz$'`" = "" ] && EXT='.tgz'
[ "$EXT" = "" ] && exit 1

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

#perhaps makes following code easier if do this...
if [ "$EXT" = ".tgz" ];then
 mv -f $TARBALL $DIRPKG/${BASEPKG}.tar.gz
 TARBALL="$DIRPKG/${BASEPKG}.tar.gz"
 EXT='.tar.gz'
fi

#if tarball expands direct to '/' want to wrap around it (slackware pkg)... 100628 add -z ...
if [ "`tar -z --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 $DIRPKG/${BASEPKG}.tar.gz $DIRPKG/$BASEPKG/
 #can put other files in here if want...
 
 tar --remove-files -c -f $DIRPKG/${BASEPKG}.tar $DIRPKG/$BASEPKG/
 gzip $DIRPKG/${BASEPKG}.tar
 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###
