#!/bin/sh

#source for downloading missing archives
sourcelink="http://ossasepia.com/eulora2/"

#trusted V-signature
trustedsig="Diana Coman (V-versioning 'verything.) <noemail@someemail.com>"
trustedkey="diana_coman_dev.asc"

#required files
#GNAT
#gnatdir="gcc47" # from GCC 4.7.4 GNAT on CentOS 6 efforts
gnatdir="gnat"
gnatfile="${gnatdir}.tar.gz"
#CAL3D
cal3ddir="cal3d"
cal3dfile="${cal3ddir}.tar.gz"
#CS
csdir="cs"
csfile="${csdir}.tar.gz"
#EULORA client code
euloradir="euloraclient"
eulorafile="${euloradir}.tar.gz"
play="play.sh"
#EULORA client data
edatadir="euloradata"
edatafile="euloradata.tar.gz"

#default install in current directory
prefix=$(pwd)

#if user provided a different directory, use THAT ONE
if [ "$#" -ge 1 ]; then
	prefix=$1
fi

#function to check for a file and exit if missing
exists_or_exit() {
	if [ -f "$1" ]; then
		echo "Found $1."
	else
		echo "FAILED to find locally required file $1. Please copy it to $prefix and launch this script again."
		exit
	fi
}

#function to check for a file and keep trying to download it if missing
#NB: this also downloads and checks the sig for the file
exists_or_download() {
	# exists means it verifies the sig, too
	if [ -f "$1" ]; then
		res=$(gpg --verify $1.sig $1 2>&1 | grep "Good signature from \"${trustedsig}\"")
		if [ -z "$res" ]; then
			echo "FAILED sig check for $1, will delete the corrupted file(s)."
			execute_and_check "rm $1 $1.sig"
		else
			echo "PASSED sig check for $1, moving on."
		fi
	fi

	while [ ! -f "$1" ]; do
		echo "FAILED to find locally required file $1. Will attempt to download it from ${sourcelink}."
		execute_and_check "wget -O $1 ${sourcelink}$1"
		if [ ! -f "$1.sig" ]; then
			execute_and_check "wget -O $1.sig ${sourcelink}$1.sig"
		fi
		echo "CHECKING the signature for $1"
		res=$(gpg --verify $1.sig $1 2>&1 | grep "Good signature from \"${trustedsig}\"")
		if [ -z "$res" ]; then
			echo "FAILED sig check for $1, will delete the corrupted file(s)."
			execute_and_check "rm $1 $1.sig"
		else
			echo "PASSED sig check for $1, moving on."
		fi
	done
}

#function to check result of last command and echo but NOT exit
execute_and_check() {
	cmd=$1
	echo "Executing: '$cmd'"
	$cmd
	if [ $? -ne 0 ]; then
		echo "FAILED: $cmd"
	fi
}

#function to check result of last command and EXIT if failed
execute_or_exit() {
	cmd=$1
	echo "Executing: '$cmd'"
	$cmd
	if [ $? -ne 0 ]; then
		echo "FAILED: $cmd"
		exit
	fi
}

#inform and ask for user's confirmation
ok=0
while [ $ok -ne 1 ]; do
	read -p "Will attempt to install Eulora to ${prefix}. This will *delete* any existing $gnatdir $cal3ddir $csdir $euloradir $edatadir current directories at this location. Proceed (y/n)?" yn
	case $yn in 
		[Yy]* )
			echo "Proceeding..."
			ok=1
		;;
		[Nn]* )
			echo "Aborting. You can specify a different location as input parameter to this script."
			exit
		;;
	esac
done

#go to desired location
cd $prefix

##check for needed files and complain if not available
#exists_or_exit $gnatfile
#exists_or_exit $cal3dfile
#exists_or_exit $csfile
#exists_or_exit $eulorafile
#exists_or_exit $edatafile

#check for needed files and download if not available/signatures not matching
#first the key since it's needed to check everything else; NO sig for the keyfile!
execute_and_check "wget -O ${trustedkey} ${sourcelink}${trustedkey}"
#import the key but don't be too bothered if it fails, it may be imported already
execute_and_check "gpg --import ${trustedkey}"

#(re-)download ALL sigs and overwrite any existing ones
execute_and_check "wget -O ${edatafile}.sig ${sourcelink}${edatafile}.sig"
execute_and_check "wget -O ${eulorafile}.sig ${sourcelink}${eulorafile}.sig"
execute_and_check "wget -O ${csfile}.sig ${sourcelink}${csfile}.sig"
execute_and_check "wget -O ${cal3dfile}.sig ${sourcelink}${cal3dfile}.sig"
execute_and_check "wget -O ${gnatfile}.sig ${sourcelink}${gnatfile}.sig"

#then all the archives (from small to big)
exists_or_download "${edatafile}"
exists_or_download "${eulorafile}"
exists_or_download "${csfile}"
exists_or_download "${cal3dfile}"
exists_or_download "${gnatfile}"

#all files exist so unpack and go
#1. GNAT
echo "Preparing GNAT ..."
rm -rf $gnatdir
tar -mxzvf $gnatfile

# post binutils breakage we're forced to use system's linker as its basic libs include a new relocation type - uncomment next line if you are on a newer system
#rm ${gnatdir}/libexec/gcc/x86_64-pc-linux-gnu/4.9.4/ld

#for GNAT, ALL that needs doing is exporting PATH and LD_LIBRARY_PATH
echo "Setting up PATH and LD_LIBRARY_PATH to use GNAT's gcc and gprbuild..."
#export ADALIB_PATH=${prefix}/${gnatdir}/lib/gcc/x86_64-unknown-linux-gnu/4.7.4/adalib
export ADALIB_PATH=${prefix}/${gnatdir}/lib/gcc/x86_64-pc-linux-gnu/4.9.4/adalib
export PATH=${prefix}/${gnatdir}/bin:$PATH
## Need to disable this (LD_LIBRARY_PATH) on newer systems because mesa/gallium demands the system's newer libstdc++; gprbuild -R is also needed so this path doesn't come in again via RPATH.
## Unfortunately it's still required for older systems because things built with the newer Adacore toolchain won't then work with system's libstdc++.
export LD_LIBRARY_PATH=${prefix}/${gnatdir}/lib64:$LD_LIBRARY_PATH
echo $PATH
echo $LD_LIBRARY_PATH

#2. Cal3d
echo "Preparing Cal3D ..."
rm -rf $cal3ddir
execute_or_exit "tar -mxzvf $cal3dfile"
cd $cal3ddir
execute_or_exit "autoreconf --install --force"
execute_or_exit "./configure --prefix=${prefix}/${cal3ddir}"
execute_or_exit "make -j$(nproc)"
execute_or_exit "make install"

echo "Updating CAL3D and LD_LIBRARY_PATH environment vars"
export CAL3D="${prefix}/${cal3ddir}"
export LD_LIBRARY_PATH="${prefix}/${cal3ddir}/lib:$LD_LIBRARY_PATH"
echo "Done."
cd ../

#3. CS
echo "Preparing CrystalSpace ..."
rm -rf $csdir
execute_or_exit "tar -mxzvf $csfile"
cd $csdir
execute_or_exit "./configure --without-java --without-perl --without-python --without-3ds --with-cal3d=$CAL3D"
execute_or_exit "jam -aq -j$(nproc) libs plugins cs-config"
echo "Updating CRYSTAL and LD_LIBRARY_PATH environment vars"
export CRYSTAL="${prefix}/${csdir}"
export LD_LIBRARY_PATH="${prefix}/${csdir}:$LD_LIBRARY_PATH"
echo "Done."
cd ../

#4. Eulora's client - code and data
echo "Preparing Eulora ..."
rm -rf $euloradir
rm -rf $edatadir
execute_or_exit "tar -mxzvf $eulorafile"
execute_or_exit "tar -mxzvf $edatafile"
mv $edatadir ${euloradir}/data
cd $euloradir
sed -i "s/gprbuild/gprbuild -R/" build.sh # required for newer systems with C++-infected graphics drivers as noted above
execute_or_exit "chmod +x build.sh"
execute_or_exit "./build.sh"

echo "Updating build and clean scripts to match the local environment"
sed -i "3 a export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}" build.sh
sed -i "4 a export PATH=${PATH}" build.sh
sed -i "5 a export CAL3D=${CAL3D}" build.sh
sed -i "6 a export CRYSTAL=${CRYSTAL}" build.sh
sed -i "7 a export ADALIB_PATH=${ADALIB_PATH}" build.sh

sed -i "3 a export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}" clean.sh
sed -i "4 a export PATH=${PATH}" clean.sh
sed -i "5 a export CAL3D=${CAL3D}" clean.sh
sed -i "6 a export CRYSTAL=${CRYSTAL}" clean.sh
sed -i "7 a export ADALIB_PATH=${ADALIB_PATH}" clean.sh
echo "Done."

echo "Creating launch script play.sh to set up the environment as required before launching eulora"
cat > $play <<EOF
#!/bin/sh
export ADALIB_PATH=$ADALIB_PATH
export CRYSTAL=$CRYSTAL
export CAL3D=$CAL3D
export PATH=$PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH
exec ./euclient "\$@"
EOF
execute_and_check "chmod +x $play"

echo "To run Eulora, simply run the $play script in $euloradir. All configuration is in euconfig.ini file, including server's IP and relevant ports (if running a firewall, you'll need to allow UDP to/from server through the chosen local ports). Enjoy!"


