#!/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 sc2/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 ../../uqm.exe ]; then
	echo "uqm.exe not found. Go build it first."
	exit 1
fi

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

echo "Building the key-jammer application..."
cd ../../../tools/keys || exit 1
build_keyjam
result=$?
cd ../../sc2/build/win32_install
if [ $result -ne 0 ] ; then
	echo "Could not build keyjam.exe. Aborting installer creation."
	exit 1
fi
cp ../../uqm.exe . || exit
strip ./uqm.exe || exit
echo "Identifying DLL dependencies..."
DLLS=$(ntldd -R uqm.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 \"uqm.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\\uqm.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 COPYING README README-SDL WhatsNew; do
	cp "../../$i" "$i.txt" && unix2dos "$i.txt"
done
cp ../../doc/users/manual.txt Manual.txt && unix2dos "Manual.txt"

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