#!/bin/sh

wildpath=""

if [ "$#" -ne "2" ] && [ "$#" -ne "1" ] ; then
    LogIt "untar-subroutine-me <archive> (<wildpath>)" 1
    LogIt "e.g. untar-subroutine-me archives/15.afio.bz2" 1
    LogIt "or   untar-subroutine-me archives/15.afio.bz2 /mnt/dos/*" 1
    exit 1
fi

archive=$1
if [ "$#" -eq "2" ] ; then
    wildpath=$2
fi

if [ ! -f "$archive" ] ; then
    LogIt "Cannot find archive $archive" 1
    exit 1
fi

# ---------------- restore a tarball --------------

cd /mnt/RESTORING
if [ "$?" -ne "0" ] ; then
    LogIt "Cannot cd to /mnt/RESTORING" 1
    exit 1
fi

setno=`echo "$archive" | sed s/.afio/'|'/ | sed s/archives/'|'/ | cut -d'|' -f2 | cut -d'/' -f2`
path=`echo "$archive" | sed s/[0-9]*.afio/'|'/ | cut -d'|' -f1`
filelist=$path/filelist.$setno

if [ "`echo "$archive" | grep "\.bz2"`" != "" ]; then
    callstr="-Z -P bzip2"
elif [ "`echo "$archive" | grep "\.lzo"`" != "" ] ; then
    callstr="-Z -P lzop"
elif [ "`echo "$archive" | grep "\.gz"`" != "" ]; then
    callstr="-Z"
#    callstr="-z"
elif [ "`echo "$archive" | grep "\.afio"`" != "" ]; then
    callstr=""
else
    LogIt "Unknown filetype - $archive" 1
    exit 1
fi

setno=`echo "$archive" | tr '/' '.' | tr '[:alpha:]' '.' --squeeze-repeats | cut -d'.' -f2`
path=`echo "$archive" | gawk '{i=split($0,res,"/");j=1;while(j<i){printf res[j]"/";j++;};}'`
#LogIt "archive = $archive"
#LogIt "path    = $path"
#LogIt "setno   = $setno"
if [ "$wildpath" = "" ] ; then
    afio -i $callstr $archive
    res=$?
    if [ ! -e "/tmp/DO-NOT-VERIFY" ] ; then
# ----verify----
	afio -r $callstr $archive
	res=$(($res+$?))
        afio -t $callstr $archive > /tmp/rsm.lst.tmp
        if [ -s "$path/cklist.$setno" ] ; then
# ----md5sum----
#	    echo -e -n "\rMD5 "
	    out=`mondo-checksum $path/filelist.$setno $path/cklist.$setno /mnt/RESTORING --verify`
	    r=$?
	    res=$(($res+$r))
	    if [ "$r" -ne "0" ] ; then 
		if [ "$out" = "" ] ; then
		    echo "Problem running mondo-checksum"
		else
		    echo -e -n "Files with bad checksums:-\
                              \n$out\n"
		fi
#	    else
#		echo -e -n "ok.\r"
	    fi
        fi
    fi
else
    if [ "`cat $filelist | grep "$wildpath"`" = "" ] ; then
	LogIt "Set $setno contains no files matching $wildpath"
    else
	LogIt "`grep -n "$wildpath" $filelist | tail -n1 | cut -d':' -f1` matches in set $setno"
	afio -i -v -y $wildpath"*" $callstr $archive
	res=$?
	if [ ! -e "/tmp/DO-NOT-VERIFY" ] ; then
	    afio -r -y $wildpath $callstr $archive
	    res=$(($res+$?))
	fi
    fi
fi

exit $res
