#!/usr/bin/sh

for i in uqm-installer.nsi packages.nsh orzshofixti.bmp ultron.bmp \
	 uqm-3do.cfg uqm-pc.cfg; do
	if ! [ -f $i ]; then
		echo "$i not found. Make sure you are running from build/win32_install."
		exit 1
	fi
done
if ! [ -f packages.nsh ]; then
	echo "packages.nsh not found. Follow the instructions in INSTALL.pkgs"
	echo "to regenerate it."
	exit 1
fi
if ! [ -f ../../UrQuanMasters.exe ]; then
	echo "UrQuanMasters.exe not found. Go build it first."
	exit 1
fi

build_keyjam()
{
	make clean && \
	make && \
	strip keyjam.exe && \
	cp keyjam.exe ../../build/win32_install
	return $?
}

if ! [ -f ./keyjam.exe ]; then
	echo "Building the key-jammer application..."
	cd ../../tools/keys || exit 1
	build_keyjam
	result=$?
	cd ../../build/win32_install
	if [ $result -ne 0 ] ; then
		echo "Could not build keyjam.exe. Aborting installer creation."
		exit 1
	fi
fi

if ! [ -f ./UrQuanMasters.exe ]; then
	cp ../../UrQuanMasters.exe . || exit
	strip ./UrQuanMasters.exe || exit
fi

echo "Identifying DLL dependencies..."
DLLS=$(ntldd -R UrQuanMasters.exe | awk '/\\bin\\/{print $3;}')
DLLS2=$(ntldd -R keyjam.exe | awk '/\\bin\\/{print $3;}')
DLLS="$DLLS $DLLS2"
DLLS=$(for dll in $DLLS; do echo $dll; done | sort -u)

(echo "# Autogenerated by build-win32-installer.sh";
 echo "#"
 echo "    File \"UrQuanMasters.exe\""
 echo "    File \"keyjam.exe\""
 for dll in $DLLS; do
	echo "    File \"$dll\""
 done) >> dlls.nsi

(echo "# Autogenerated by build-win32-installer.sh";
 echo "#"
 echo "    Delete \"\$INSTDIR\\UrQuanMasters.exe\""
 echo "    Delete \"\$INSTDIR\\keyjam.exe\""
 for dll in $DLLS; do
	 echo "    Delete \"\$INSTDIR\\$(basename $dll)\""
 done) >> undlls.nsi

echo "Preparing documentation..."
for i in AUTHORS.txt COPYING.txt MegaMod-README.txt UQM-README.txt README-SDL.txt UQM-Manual.txt CHANGELOG.txt UQM-Manual.txt; do
	cp "../../doc/release/$i" "$i"
done

echo "Creating installer..."
makensis "-XSetCompressor /SOLID lzma" uqm-installer.nsi || exit 1
echo "Installer has been created successfully."
