#!/bin/bash
cat <<EOD
This game requires Adobe AIR to be installed.

Could not find the Adobe AIR runtime in /opt/Adobe AIR/
If you have already installed Adobe AIR, make sure the runtime is placed
in /opt/Adobe AIR/ (e.g. by either copying or symlinking it), so that
	/opt/Adobe AIR/Versions/1.0/libCore.so
exists and then re-run this game.

EOD

read -p "Do you want to install the Adobe AIR runtime now? [Y/n] "
[ -z "$REPLY" ] && REPLY=y
case "$REPLY" in
	Y*|y*)  ;;
	*) exit 2 ;;
esac

ARCH="$(uname -m)"
GAMEDIR="$(cd "${0%/*}" && echo $PWD)"
export FOO=BAR
# Hmm..
# exit 1

# download AIR installer if it isn't here yet
if [ ! -f ./AIR/AdobeAIRInstaller.bin ]; then
	echo "Adobe AIR Installer not found in $GAMEDIR/AIR/, downloading..."
	wget -O ./AIR/AdobeAIRInstaller.bin \
	     "http://airdownload.adobe.com/air/lin/download/2.6/AdobeAIRInstaller.bin"
	if [ $? -ne 0 ]; then
		echo "ERROR:"
		echo "Could not download the installer." >&2
		echo "Please manually download it from" >&2
		echo "http://airdownload.adobe.com/air/lin/download/2.6/AdobeAIRInstaller.bin" >&2
		echo "and move it to $GAMEDIR/AIR/AdobeAIRInstaller.bin" >&2
		exit 7
	fi
fi

find_lib() {
	if [ "$ARCH" = "x86_64" ]; then
		/sbin/ldconfig -p | fgrep "$1" | fgrep -m 1 x86-64 | awk '{print $NF}'
	else
		/sbin/ldconfig -p | fgrep -m 1 "$1" | awk '{print $NF}'
	fi
}

# add directory containing libs we ship for the installer
# we have to specify an absolute path, because the AIR installer
# switches the working directory
LIB_PATHS="$GAMEDIR/lib32"
# try to figure out where the gnome keyring/kwallet libraries for the
# actual system architecture are, so the installer can load them (since it
# tries to load them manually ...)
# TODO: not sure yet if the 32bit installer needs this
KEYRING="$(find_lib libgnome-keyring.so)"
if [ -n "$KEYRING" ]; then
	LIB_PATHS="$(dirname "$KEYRING"):$LIB_PATHS"
fi
# TODO: find actual library name AIR is looking for (qdbus?!)
KWALLET="$(find_lib kwallet)"
if [ -n "$KWALLET" ]; then
	LIB_PATHS="$(dirname "$KWALLET"):$LIB_PATHS"
fi

export LD_LIBRARY_PATH="$LIB_PATHS${LD_LIBRARY_PATH+:$LD_LIBRARY_PATH}"
chmod +x ./AIR/AdobeAIRInstaller.bin
./AIR/AdobeAIRInstaller.bin
if [ $? -ne 0 ]; then
	echo "ERROR:" >&2
	echo "Installation of AIR failed! Please consult the installation log" >&2
	echo "$HOME/.appdata/Adobe/AIR/Logs/Install.log" >&2
	read -p "Do you want to see the installation log now? [Y/n] " >&2
	[ -z "$REPLY" ] && REPLY=y
	case "$REPLY" in
		Y*|y*)
			cat $HOME/.appdata/Adobe/AIR/Logs/Install.log >&2 ;;
	esac
	read
	exit 1
fi
