#!/usr/bin/env bash
# Create a staged zip file

# Change a possibly-relative pathname to a full pathname.
function repath
{
	case $1 in
	/*)	echo "$1"
		;;
	*)	echo "$PWD/$1"
		;;
	esac
}

# Pick off '-c'
if [ "X$1" = "X-c" ]
then	comment="$2"
	shift 2
fi

# Pick off '-o'
if [ "X$1" = "X-o" ]
then	ofile="$(repath $2)"
	shift 2
fi

if [ $# -ne 1 ]
then	echo >&2 "Usage: ZipIt [-c comment] [-o ofile] template-file"
	exit 1
fi

zd=/tmp/zi$$
rm -rf $zd
trap "rm -rf $zd" EXIT
trap "exit 0" INT
mkdir $zd

exec 5<$1 || exit 1
while read -u5 kw p1 p2 p3
do	case "$kw" in
	\#*)	;;
	O)	# Output file
		if [ -z "$p1" ]
		then	echo >&2 "Missing parameter for O"
			exit 1
		fi
		if [ -n "$p2" ]
		then	echo >&2 "Too many parameters for O"
			exit 1
		fi
		ofile=$(repath $p1)
		;;
	D)	# Create subdir
		if [ -z "$p1" ]
		then	echo >&2 "Missing parameter for D"
			exit 1
		fi
		if [ -n "$p2" ]
		then	echo >&2 "Too many parameters for D"
			exit 1
		fi
		mkdir -p $zd/$p1
		;;
	F)	# File
		if [ -z "$p1" ]
		then	echo >&2 "Missing parameter(s) for F"
			exit 1
		fi
		if [ -z "$p2" ]
		then	p2=$p1
		fi
		if [ -n "$p3" ]
		then	echo >&2 "Too many parameters for F"
			exit 1
		fi
		if [ ! -f "$p1" ]
		then	echo >&2 "No such file: $p1"
		    	exit 1
		fi
		ln -s $(repath $p1) $zd/$p2
		;;
	*)	echo >&2 "Unknown keyword '$kw'"
		exit 1
	esac
done
if [ -z "$ofile" ]
then	echo >&2 "Must specify output file"
	exit 1
fi

cd $zd
if [ -n "$comment" ]
then	echo "$comment" | zip -r -z -X $ofile .
else	zip -r -X $ofile .
fi
cd -
