#!/bin/sh

# Yet Another Useless Shell Script 
# (self-extracting archive generator)
#
# Licensed under the NWL - No Whining License.
#
# You may use this, modify this, redistribute this provided you agree to:
# - not whine about it;
# - the fact that there is no warranty of any kind.
# - retain this copyright in full.
#
# Written by Anicka Bernathova <anicka@anicka.net> in 2007


usage()
{
cat <<EOW
Usage: genarchive [-e path_to_executable_post-extract_script] archive_name file_to_archive 
EOW
}

while getopts ":e:h" options; do
  case $options in
    e ) script="$OPTARG";;
    h ) usage ; exit 0 ;;
    ? ) usage ; exit 1 ;;
    * ) usage ; exit 1 ;;
  esac
done

shift $(($OPTIND - 1))

if [ -z "$2" ]; then
	usage	
	exit 0
fi

output="$1"
dir="$2"

if [ ! -e "$dir" ]; then
	echo "Bad command or file name :-D" >&2
	exit 1
fi

dir="$dir/"
case $dir in
	../* | */../* )
		echo ".. in path not supported" >&2
		exit 1
	;;
	/* )
		echo "Absolute path not supported" >&2
		exit 1
	;;
esac

normalize()
{
	sed '
		:loop
		s@\(^|/\)\./@\1@
		s@\(^|/\)[^/]+/\.\./@\1@
		s@//@/@
		tloop
	'
}

if [ -n "$script" ]; then
	if [ ! -x "$script" -o ! -f "$script" ]; then
		echo "The script must be an executable file" >&2 
	fi

	nscript=`echo $script | normalize`
	ndir=`echo $dir | normalize`
	if [ "${nscript:0:${#ndir}}" != "$ndir" ]; then
		echo "The script does not seem to be among the files to archive" >&2	
	fi			
fi

if_script()
{
	[ -z "$script" ] || echo && echo "$@"
}

cat <<EOF >$output
#!/bin/bash

usage()
{
cat <<UA
Usage: $output [-C directory] [-lvh]`if_script "Will run $script"`
UA
}

cmds="xzf"
destdir=.

while getopts ":C:lvh" options; do
  case \$options in
    l ) cmds=\${cmds/x/t}
	;;
    v ) cmds="v"\$cmds;;
    C ) cmd2="-C \$OPTARG -"
	destdir="\$OPTARG"
	;;
    h ) usage
	exit 0;;
    ? ) usage
        exit 1;;
    * ) usage
        exit 1;;
  esac
done

command="tar \$cmd2\$cmds -"

uudecode <<EOW | \$command 
EOF
tar czf - $dir | uuencode -m - >>$output 
echo EOW >>$output 
[ -z "$script" ] || cat <<EOF >>$output
if [ \${cmds/t/} == \$cmds ] ; then
	echo "Running $script..."
	\$destdir/$script
else
	echo "Will run $script after extraction"
fi
EOF

chmod a+x $output
