#!/bin/sh

INSTALLER_PATH="$1"

print_usage() {
	echo "Usage: "
	echo "  $0 /path/to/setup_daikatana_2.0.0.3.exe"
}

print_bug_info() {
	echo "Please report this as a bug to the Daikatana 1.3 Team's issue tracker:"
	echo "https://bitbucket.org/daikatana13/daikatana/issues"
}

if [ -z "$INSTALLER_PATH" ]; then
	echo "Extractor for GOG.com Daikatana installer using innoextract"
	echo "It will extract the relevant game data to this directory"
	echo "so it can be used with Daikatana 1.3"
	echo "NOTE: This only works with the GOG.com installer,"
	echo "      not the CD version or any other version of Daikatana!"

	print_usage

	exit 1
fi

if [ ! -e "$INSTALLER_PATH" ]; then
	echo "ERROR: The file $INSTALLER_PATH doesn't exist!"
	print_usage

	exit 1
fi

mkdir install_tmp

echo "Extracting installer:"
./innoextract --silent --progress --color --lowercase --gog --output-dir ./install_tmp "$INSTALLER_PATH"

if [ $? -ne 0 ]; then
	echo "ERROR: Extracting failed for unknown reason!"

	print_bug_info

	rm -r ./install_tmp
	exit 1
fi

if [ ! -d ./install_tmp/ ]; then
	echo "ERROR: Unable to find install_tmp directory!"

	print_bug_info

	echo "However, you can find the unextracted data in ./installer_tmp/"
	echo "Maybe you can find the data/ directory somewhere in there."
	echo "It should contain a file named pak1.pak, amongst other things."
	exit 1
fi

# we already have a data directory, probably with patched files, copy those over data/ from installer
if [ -d ./data ]; then

	echo "Patching installer's install_tmp/data/ directory with contents of 1.3 patch's ./data/"
	cp -r ./data/* ./install_tmp/app/data/

	echo "Removing path ./data/"
	rm -r ./data

fi

echo "Moving install_tmp/app/data/ from installer to ./data/"
mv ./install_tmp/app/data .

echo "Retrieving manual from installer"
mv ./install_tmp/app/*.pdf .

echo "Cleaning up unused files from installer"
rm -r ./install_tmp

exit 0
