#!/bin/bash

: ${MAKESELF:=/usr/share/loki-setup/makeself}
: ${SETUPIMAGE:=/usr/share/loki-setup/image}

: ${VERSION:=0.0_`date +%Y%m%d%H%M`}
: ${RELEASE:=0}

set -e
set -x

shopt -s nullglob

rm -rf image
mkdir image

### loki-setup files
cp -a $SETUPIMAGE/{setup.data,setup.sh} image/

### splash
rm -f image/setup.data/splash.xpm
[ -e splash.xpm ] && cp splash.xpm image/setup.data/splash.xpm
rm -f image/turtlearena.png
cp ../quake3.png image/turtlearena.png

### binaries
# engine top directory
topdir="../.."

echo "changequote(\`[', \`]')dnl" > defines.m4
echo "define(VERSION,$VERSION)dnl" >> defines.m4

copystartscript()
{
	local arch="$1"
	mkdir -p image/bin/Linux/$arch
	if [ "$arch" = x86_64 ]; then
		ln -s x86_64 image/bin/Linux/amd64
	elif [ "$arch" = ppc ]; then
		ln -s ppc image/bin/Linux/ppc64
	fi
	install -m 755 turtlearena.sh image/bin/Linux/$arch/turtlearena
}

archs=()
for arch in $topdir/build/release-*; do
	arch=${arch##*-}
	case "$arch" in
		i386) echo "define(HAVE_I386,yes)dnl" >> defines.m4
			copystartscript x86
		;;
		x86_64) echo "define(HAVE_X86_64,yes)dnl" >> defines.m4
			copystartscript $arch
		;;
		ppc) echo "define(HAVE_PPC,yes)dnl" >> defines.m4
			copystartscript $arch
		;;
		ppc64) echo "define(HAVE_PPC64,yes)dnl" >> defines.m4
			copystartscript $arch
		;;
		*)
			echo "architecture $arch unsupported"
			continue;
		;;
	esac
	archs[${#archs[@]}]=$arch
done

for arch in "${archs[@]}"; do
	dst=image/tmp
	mkdir $dst
	mkdir $dst/base
	install -m 755 $topdir/build/release-linux-$arch/turtlearena.$arch $dst/turtlearena.$arch
	install -m 755 $topdir/build/release-linux-$arch/turtlearena-server.$arch $dst/turtlearena-server.$arch

	tar --owner=root --group=root -C $dst -cf ./image/turtlearena.$arch.tar .
	rm -rf ./image/tmp
done

### uninstall script
install -m 755 ./preuninstall.sh image/preuninstall.sh

# desktop file handling
install -m 755 ./install-desktop-files.sh image/install-desktop-files.sh
install -m 755 /usr/bin/xdg-desktop-menu image/xdg-desktop-menu
install -m 644 turtlearena.desktop image/turtlearena.desktop.in

### README, COPYING and EULA
install -m 644 ../$topdir/INSTALLER_README.txt image/README
install -m 644 ../$topdir/GPL-2.txt image/GPL-2
install -m 644 ../$topdir/CC-BY-SA-3.0.txt image/CC-BY-SA-3.0
install -m 644 ../$topdir/COPYRIGHTS.txt image/COPYRIGHTS
install -m 644 ../$topdir/CREDITS.txt image/CREDITS
mkdir image/base
install -m 644 ../$topdir/install/base/assets0.pk3 image/base/assets0.pk3
install -m 644 ../$topdir/install/base/assets1-qvms.pk3 image/base/assets1-qvms.pk3
install -m 644 ../$topdir/install/base/assets2-music.pk3 image/base/assets2-music.pk3

# create setup.xml
m4 defines.m4 setup.xml.in > image/setup.data/setup.xml

### makeself installer
ARCH=
if [ "${#archs[@]}" -eq 1 ]; then
	ARCH=.$arch
fi
$MAKESELF/makeself.sh image turtlearena-$VERSION-$RELEASE$ARCH.run "turtlearena $VERSION-$RELEASE" ./setup.sh
