#!/bin/sh
WORKDIR=`pwd`/tarexectemp

rm -rf "$WORKDIR"
mkdir "$WORKDIR"

TARFILE=`readlink -f "$1"`
FILELIST=`tar tf "$TARFILE" 2>&1 | tee "$WORKDIR/test1.txt" > /dev/null`
RETCODE=$?

if [ "$RETCODE" -eq 0 ]
then
	BADFILES=`( for f in $FILELIST ; do echo $f ; done ) | egrep -v '^app/|^filesystem/|^script/$|^script/before$|^script/after$|^script/superuser$'`

	if [ -n "$BADFILES" ]
	then
		echo "Found disallowed files: $BADFILES"
		exit 2
	fi
	
	NUMSU=`( for f in $FILELIST ; do echo $f ; done ) | egrep '^script/superuser$' | wc -l`
	
	if [ "$NUMSU" -ne 0 ]
	then
		TARCMD='sudo tar'
	else
		TARCMD=tar
	fi

	NUMBEFORE=`( for f in $FILELIST ; do echo $f ; done ) | egrep '^script/before$' | wc -l`
	NUMAFTER=`( for f in $FILELIST ; do echo $f ; done ) | egrep '^script/after$' | wc -l`
	NUMAPP=`( for f in $FILELIST ; do echo $f ; done ) | egrep '^app/.+' | wc -l`
	NUMFS=`( for f in $FILELIST ; do echo $f ; done ) | egrep '^filesystem/.+' | wc -l`

	if [ "$NUMAPP" -ne 0 ]
	then
		if [ ! -d /home/smc ]
		then
			echo "Directory /home/smc does not exist!"
			exit 3
		fi
	fi

	if [ "$NUMBEFORE" -ne 0 ]
	then
		( cd "$WORKDIR"
		  $TARCMD xf "$TARFILE" script/before --strip=1
		  RETCODE=$?
		  if [ "$RETCODE" -eq 0 ]
		  then
			./before
			RETCODE=$?
		  fi
		  exit $RETCODE
		)
		RETCODE=$?
		if [ "$RETCODE" -ne 0 ]
		then
			echo "before script failed with code $RETCODE"
			rm -rf "$WORKDIR"
			exit 3
		fi
	fi

	if [ "$NUMAPP" -ne 0 ]
	then
		( cd /home/smc
		  $TARCMD xvf "$TARFILE" --wildcards 'app/*' --strip=1 2>&1 | tee "$WORKDIR/appfiles.txt" > /dev/null
		)
		RETCODE=$?
		if [ "$RETCODE" -ne 0 ]
		then
			cat "$WORKDIR/appfiles.txt"
			echo "app file extraction failed with code $RETCODE"
			rm -rf "$WORKDIR"
			exit 3
		fi
	fi

	if [ "$NUMFS" -ne 0 ]
	then
		( cd / 
		  $TARCMD xf "$TARFILE" --wildcards 'filesystem/*' --strip=1 2>&1 | tee "$WORKDIR/fsfiles.txt" > /dev/null
		)
		RETCODE=$?
		if [ "$RETCODE" -ne 0 ]
		then
			cat "$WORKDIR/fsfiles.txt"
			echo "filesystem file extraction failed with code $RETCODE"
			rm -rf "$WORKDIR"
			exit 3
		fi
	fi

	if [ "$NUMAFTER" -ne 0 ]
	then
		( cd "$WORKDIR"
		  $TARCMD xf "$TARFILE" script/after --strip=1
		  RETCODE=$?
		  if [ "$RETCODE" -eq 0 ]
		  then
			./after
			RETCODE=$?
		  fi
		  exit $RETCODE
		)
		RETCODE=$?
		if [ "$RETCODE" -ne 0 ]
		then
			echo "after script failed with code $RETCODE"
			rm -rf "$WORKDIR"
			exit 3
		fi
	fi

	rm -rf "$WORKDIR"
	exit 0
else
	cat "$WORKDIR/test1.txt"
	echo "tar archive test returned $RETCODE"
	rm -rf "$WORKDIR"
	exit $RETCODE
fi


