#!/bin/bash

acsdata=$(tempfile)
libname=$(basename $acsdata |head -c8)

echo -n "wad name: "
read name_of_wad

if [ -z "$name_of_wad" ]
then
	name_of_wad=$acsdata
fi

if [ $(echo -n $name_of_wad |tail -c4) = ".pk3" ]
then
	name_of_wad="${name_of_wad}.pk3"
fi

echo "using $name_of_wad as example WAD name"

zipname="${HOME}/Desktop/$name_of_wad"

if [ -f "$zipname" ]
then
	echo "$zipname already exists" >/dev/null
	rm -v $acsdata
	exit 1
fi

vim $acsdata

if [ "$(wc -c $acsdata)" = "0" ]
then
	echo "abort: no acs given" >/dev/null
fi

tmpdir=$(tempfile)
rm -f $tmpdir
mkdir $tmpdir
pushd $tmpdir
	mkdir acs acs_src
	echo "#include \"zcommon.acs\"" >>acs_src/scripts.acs
	echo "#library \"$libname\"" >>acs_src/scripts.acs
	cat ${acsdata} >>acs_src/scripts.acs

	built=0
	while [ ! -f acs/${libname}.o ]
	do
		acc -I ${HOME}/doom/acs acs_src/scripts.acs acs/${libname}.o

		if [ ! -f acs/${libname}.o ]
		then
			echo -n "failed to build, please re-check your source: "
			read answer
			vim acs_src/scripts.acs
		fi
	done

	echo "${libname}" >loadacs.txt
	zip -r9 ${zipname} *
popd

rm -rv $tmpdir
rm -v $acsdata

