#!/bin/bash
set -e

SELF=$0
SELF_PARAMETERS=$@

# == Settings ==

DOWNLOAD_MIRROR=${DOWNLOAD_MIRROR:-""}

TARGET_OS=${TARGET_OS:-"$(uname -s)"}
TARGET_CPU=${TARGET_CPU:-"$(uname -p)"}

if [[ "${TARGET_CPU}" == "x86_64" || "${TARGET_CPU}" == "i686" ]]; then
	TARGET_CPU="x86_glibc21"
fi
ARCHITECTURE="${TARGET_OS,,}_${TARGET_CPU,,}"

UPDATE_FILE_BIN="live_${ARCHITECTURE}.txt"
UPDATE_FILE_DATA="dsbuild.bz2.txt"

if [[ $EUID == 0 ]]; then
	DEFAULT_DATADIR="/usr/local/games/dockingstation"
	DEFAULT_BINDIR="/usr/local/bin"
else
	if [[ ! -z "${XDG_DATA_HOME}" ]]; then
		DEFAULT_DATADIR="${XDG_DATA_HOME}/dockingstation"
	else
		DEFAULT_DATADIR="${HOME}/.local/share/dockingstation"
	fi
	if [[ ! -z "${XDG_BIN_HOME}" ]]; then
		DEFAULT_BINDIR="${XDG_BIN_HOME}"
	else
		DEFAULT_BINDIR="${HOME}/.local/bin"
	fi
fi

# == Get Game Locations ==

# Feb. 17, 2000 - Sam Lantinga, Loki Entertainment Software
FindPath()
{
    fullpath="`echo $1 | grep /`"
    if [ "$fullpath" = "" ]; then
        oIFS="$IFS"
        IFS=:
        for path in $PATH
        do if [ -x "$path/$1" ]; then
               if [ "$path" = "" ]; then
                   path="."
               fi
               fullpath="$path/$1"
               break
           fi
        done
        IFS="$oIFS"
    fi
    if [ "$fullpath" = "" ]; then
        fullpath="$1"
    fi
    # Is the awk/ls magic portable?
    if [ -L "$fullpath" ]; then
        fullpath="`ls -l "$fullpath" | awk '{print $11}'`"
    fi
    dirname $fullpath
}

if which dockingstation >/dev/null 2>&1; then
	BIN_EXECUTABLE=`type -p dockingstation`
	BIN_DEST=`dirname "${BIN_EXECUTABLE}"`
	INSTALL_DEST=`FindPath "${BIN_EXECUTABLE}"`
fi

[ -L "${SELF}" ] && INSTALL_DEST=`FindPath ${SELF}`
INSTALL_DEST="${INSTALL_DEST:-$DEFAULT_DATADIR}"
INSTALL_DEST=${INSTALL_DEST%/}

[ -L "${SELF}" ] && BIN_DEST=`dirname ${SELF}`
BIN_DEST="${BIN_DEST:-$DEFAULT_BINDIR}"
BIN_DEST=${BIN_DEST%/}

if [[ -z "$C3_MAIN" || ! -d "$C3_MAIN" ]]; then
	if which creatures3 >/dev/null 2>&1; then
		C3_EXECUTABLE=`type -p creatures3`
		C3_MAIN=`FindPath "${C3_EXECUTABLE}"`
	fi
fi
if [[ -z "$C3_MAIN" || ! -d "$C3_MAIN" ]]; then
	C3_MAIN="/usr/local/games/creatures3"
fi

# == Installation Media ==

if [[ -z "$CD_PATH" && -e "`FindPath ${SELF}`/cdtastic" ]]; then
	CD_PATH="`FindPath ${SELF}`"
	if ! echo "$CD_PATH" | egrep "^/" >/dev/null; then
		CD_PATH="`pwd`/$CD_PATH"
	fi
	CD_PATH=`echo "$CD_PATH" | sed "s/\/\$//"`
fi

# == Functions ==

function download_fail()
{
	echo
	if [[ -e "${INSTALL_DEST}/${UPDATE_FILE_DATA}" ]]; then
		echo "Docking Station failed to update from the internet. Either"
		echo "you are not connected to the internet or the update server is"
		echo "down. Please try again later."
		echo
		echo "You can run the game without checking for updates by typing"
		echo -ne '\033]0;\w\007\033[32mdockingstation nocheck\033[0m'
		echo "."
	else
		echo "Docking Station failed to install from the internet. Either"
		echo "you are not connected to the internet or the update server is"
		echo "down. Please try again later."
	fi
	exit 1
}

function download()
{
	SRCFILE=$1
	DSTFILE=$2
	
	if [[ -e "${DSTFILE}" ]]; then
		rm -f "${DSTFILE}"
	fi

	if [[ -z "${CD_PATH}" ]]; then
		if which wget >/dev/null 2>&1; then
			if ! wget -O "${DSTFILE}" "${DOWNLOAD_MIRROR}${SRCFILE}"; then
				download_fail
			fi
		elif which curl >/dev/null 2>&1; then
			if ! curl -L -o "${DSTFILE}" "${DOWNLOAD_MIRROR}${SRCFILE}"; then
				download_fail
			fi
		else
			echo "You need either wget or curl installed. These are standard"
			echo "pieces of software which you should be able to install using"
			echo "the normal method for your distribution."
			exit 1
		fi
	else
		cp "${CD_PATH}/${SRCFILE}" "${DSTFILE}"
	fi
}

function decompress()
{
	if [[ -e "$1" ]]; then
		rm -f "$1"
	fi

	if ! which bunzip2 >/dev/null 2>&1; then
		echo
		echo "You need to have bunzip2 installed. This is a standard piece of"
		echo "software which you should be able to install using the normal"
		echo "method for your distribution."
		exit 1
	fi
	bunzip2 "$1.bz2"
}

function check_writeable()
{
	if [[ ! -d "$1" ]]; then
		echo
		echo "Directory $1 doesn't exist, or is a file."
		echo "Try making it and running the script again."
		exit 1
	fi
	if [[ ! -w "$1" ]]; then
		echo
		echo "You do not have write access to $1."
		echo "Try fixing permissions or using a different path."
		exit 1
	fi
}

function process_file_list_download
{
	COUNT=0
	while read FULL_SIZE SQUASH_SIZE REMOTE_SUM FILE_NAME; do
		COUNT=$((COUNT+1))
		echo "${COUNT}/$2 ${FILE_NAME}..."

		FILE_DIR=`dirname "${FILE_NAME}"`
		FILE_LOWER=`basename "${FILE_NAME}"`
		if [[ "${FILE_DIR}" == "Sounds" || "${FILE_DIR}" == "Backgrounds" || "${FILE_DIR}" == "Overlay Data" || "${FILE_DIR}" == "Body Data" || "${FILE_DIR}" == "Images" ]]; then
			FILE_LOWER="${FILE_LOWER,,}"
		fi
		if [[ "${FILE_DIR}" != "." ]]; then
			FILE_LOWER="${FILE_DIR}/${FILE_LOWER}"
		fi
		
		if [[ "${REMOTE_SUM}" == "Delete" ]]; then
			echo "  deleting..."
			if [[ -d "${FILE_LOWER}" ]]; then
				rm -d "${FILE_LOWER}" 2>/dev/null || true
			elif [[ -e "${FILE_LOWER}" ]]; then
				rm -f "${FILE_LOWER}"
			fi
		elif [[ "${REMOTE_SUM}" == "Directory" ]]; then
			if [[ ! -d "" ]]; then
				echo "  creating..."
				mkdir -p "${FILE_NAME}"
			fi
		else
			LOCAL_SUM=""

			if [[ -e "${FILE_LOWER}" ]]; then
				echo "  checking..."
				LOCAL_SUM=`md5sum -b "${FILE_LOWER}" 2>&1 | cut '-d ' -f1`
			fi

			if [[ "${REMOTE_SUM}" != "${LOCAL_SUM}" ]]; then
				if [[ -z "${CD_PATH}" ]]; then
					echo "  downloading..."
				else
					echo "  copying..."
				fi
				download "$1${FILE_NAME}.bz2" "${FILE_LOWER}.bz2"
				decompress "${FILE_LOWER}"

				echo "  verifying..."
				LOCAL_SUM=`md5sum -b "${FILE_LOWER}" 2>&1 | cut '-d ' -f1`
				if [[ "${REMOTE_SUM}" != "${LOCAL_SUM}" ]]; then
					echo "  failed"
					echo
					echo "Checksum failed after download of ${FILE_NAME}!"
					echo "  Remote Sum: $REMOTE_SUM"
					echo "  Local Sum:  $LOCAL_SUM"
					exit 1
				fi
				if file "${FILE_LOWER}" | egrep -q 'executable|shell script'; then
					echo "  chmod..."
					chmod a+x "${FILE_LOWER}"
				fi
			fi
		fi
		echo "  ok"
	done
}
function download_file_list()
{
	echo
	echo "DOWNLOADING $2"
	download "$1$2.bz2" "$2.bz2"
	decompress "$2"

	cat "$2" | tr -d "\r" | process_file_list_download "$1" `wc --lines "$2"`
}

function process_file_list_uninstall
{
	COUNT=0
	while read FULL_SIZE SQUASH_SIZE REMOTE_SUM FILE_NAME; do
		COUNT=$((COUNT+1))
		echo "${COUNT}/$1 ${FILE_NAME}..."

		FILE_DIR=`dirname "${FILE_NAME}"`
		FILE_LOWER=`basename "${FILE_NAME}"`
		if [[ "${FILE_DIR}" == "Sounds" || "${FILE_DIR}" == "Backgrounds" || "${FILE_DIR}" == "Overlay Data" || "${FILE_DIR}" == "Body Data" || "${FILE_DIR}" == "Images" ]]; then
			FILE_LOWER="${FILE_LOWER,,}"
		fi
		if [[ "${FILE_DIR}" != "." ]]; then
			FILE_LOWER="${FILE_DIR}/${FILE_LOWER}"
		fi

		if [[ "${FILE_LOWER}" != "." ]]; then
		if [[ "${REMOTE_SUM}" == "Directory" ]]; then
			echo "  deleting..."
			[ -d "${FILE_NAME}" ] && rm -d "${FILE_NAME}" 2>/dev/null || true
		elif [[ "${REMOTE_SUM}" != "Delete" ]]; then
			echo "  deleting..."
			[ -e "${FILE_LOWER}" ] && rm -f "${FILE_LOWER}"
			[ -e "${FILE_LOWER}.bz2" ] && rm -f "${FILE_LOWER}.bz2"
		fi
		fi
		
		if [[ -e "${FILE_LOWER}" ]]; then
			echo "Still Exists: ${FILE_LOWER} (${FILE_NAME})"
		fi
		if [[ -e "${FILE_NAME}" ]]; then
			echo "Still Exists: ${FILE_NAME}"
		fi
		echo "  ok"
	done
}
function uninstall_file_list()
{
	echo
	echo "READING $1"

	[ -e "$1" ] || return
	tac "$1" | tr -d "\r" | process_file_list_uninstall `wc --lines "$1"`
}

function update()
{
	echo
	echo "Docking Station"
	echo "---------------"
	echo
	update_binaries
	make_bin_link
	update_data
}

function update_data()
{
	if [[ -e "${INSTALL_DEST}/${UPDATE_FILE_DATA}" ]]; then
		CURRENT_BUILD_DATA=`cat "${INSTALL_DEST}/${UPDATE_FILE_DATA}" | tr -d "\r"`
	else
		CURRENT_BUILD_DATA=""
	fi

	TEMP_FILE=`mktemp "/tmp/${UPDATE_FILE_DATA}.XXXXXX"`
	download "${UPDATE_FILE_DATA}" "${TEMP_FILE}"
	LATEST_BUILD_DATA=`cat "${TEMP_FILE}" | tr -d "\r"`
	rm -f "${TEMP_FILE}"

	echo "Current Data Version: ${CURRENT_BUILD_DATA}"
	echo "Latest Data Version:  ${LATEST_BUILD_DATA}"
	echo

	if [[ "${CURRENT_BUILD_DATA}" == "${LATEST_BUILD_DATA}" ]]; then
		return
	fi

	check_writeable `dirname "${INSTALL_DEST}"`
	mkdir -p "${INSTALL_DEST}"
	check_writeable "${INSTALL_DEST}"

	cd "${INSTALL_DEST}"
	echo >"${INSTALL_DEST}/${UPDATE_FILE_DATA}"

	if [[ -d "Images" || -d "Backgrounds" ]]; then
		echo "Converting Images For Checksum"
		LD_LIBRARY_PATH="${INSTALL_DEST}:${LD_LIBRARY_PATH}" ./imageconvert -16 Images/* Backgrounds/*
	fi

	download_file_list "${LATEST_BUILD_DATA}/global/" "file_list.txt" .

	echo "Converting Images For Use"
	LD_LIBRARY_PATH="${INSTALL_DEST}:${LD_LIBRARY_PATH}" ./imageconvert Images/* Backgrounds/*

	echo "${LATEST_BUILD_DATA}" >"${INSTALL_DEST}/${UPDATE_FILE_DATA}"
	echo
}

function update_binaries()
{
	if [[ -e "${INSTALL_DEST}/${UPDATE_FILE_BIN}" ]]; then
		CURRENT_BUILD_BIN=`cat "${INSTALL_DEST}/${UPDATE_FILE_BIN}" | tr -d "\r"`
	else
		CURRENT_BUILD_BIN=""
	fi

	TEMP_FILE=`mktemp "/tmp/${UPDATE_FILE_BIN}.XXXXXX"`
	download "ports/${UPDATE_FILE_BIN}" "${TEMP_FILE}"
	LATEST_BUILD_BIN=`cat "${TEMP_FILE}" | tr -d "\r"`
	rm -f "${TEMP_FILE}"

	echo "Current Binary Version: ${CURRENT_BUILD_BIN}"
	echo "Latest Binary Version:  ${LATEST_BUILD_BIN}"
	echo

	if [[ "${CURRENT_BUILD_BIN}" == "${LATEST_BUILD_BIN}" ]]; then
		return
	fi

	CURRENT_INSTALLER_SUM=`md5sum -b "${SELF}" 2>&1 | cut '-d ' -f1`

	check_writeable `dirname "${INSTALL_DEST}"`
	mkdir -p "${INSTALL_DEST}"
	check_writeable "${INSTALL_DEST}"

	cd "${INSTALL_DEST}"
	echo >"${INSTALL_DEST}/${UPDATE_FILE_BIN}"

	download_file_list "ports/${LATEST_BUILD_BIN}/" "file_list_${ARCHITECTURE}.txt" .

	echo "${LATEST_BUILD_BIN}" >"${INSTALL_DEST}/${UPDATE_FILE_BIN}"

	NEW_INSTALLER_SUM=`md5sum -b "${INSTALL_DEST}/dstation-install" 2>&1 | cut '-d ' -f1`

	if grep -q Install\Blast "${INSTALL_DEST}/dstation-install"; then
		cp "${SELF}" "${INSTALL_DEST}/dstation-install"
	elif [[ "${NEW_INSTALLER_SUM}" != "${CURRENT_INSTALLER_SUM}" ]]; then
		echo "Installer is out of date. Relaunching:"
		echo "  ${INSTALL_DEST}/dstation-install"

		[ ! -z "${DOWNLOAD_MIRROR}" ] && export DOWNLOAD_MIRROR="${DOWNLOAD_MIRROR}"
		[ ! -z "${TARGET_OS}" ] && export TARGET_OS="${TARGET_OS}"
		[ ! -z "${TARGET_CPU}" ] && export TARGET_CPU="${TARGET_CPU}"
		[ ! -z "${INSTALL_DEST}" ] && export INSTALL_DEST="${INSTALL_DEST}"
		[ ! -z "${BIN_DEST}" ] && export BIN_DEST="${BIN_DEST}"
		[ ! -z "${C3_MAIN}" ] && export C3_MAIN="${C3_MAIN}"
		[ ! -z "${CD_PATH}" ] && export CD_PATH="${CD_PATH}"

		"${INSTALL_DEST}/dstation-install" ${SELF_PARAMETERS}
		exit 1
	fi
}

function make_bin_link()
{
	if [[ -d "${BIN_DEST}" ]]; then
		if [[ -w "${BIN_DEST}" ]]; then
			ln -sf "${INSTALL_DEST}/dstation-install" "${BIN_DEST}/dockingstation"
		fi
	fi
}

function uninstall()
{
	echo
	echo "Docking Station"
	echo "---------------"

	if [[ ! -e "$INSTALL_DEST" ]]; then
		echo
		echo "Installation not found:"
		echo "  ${INSTALL_DEST}"
		exit 1
	fi

	check_writeable "${INSTALL_DEST}"
	check_writeable "${BIN_DEST}"

	cd "${INSTALL_DEST}"

	echo >"${INSTALL_DEST}/${UPDATE_FILE_DATA}"
	if [[ -e "file_list.txt" ]]; then
		uninstall_file_list "file_list.txt" .
		rm -f "file_list.txt"
	fi
	rm -f "${INSTALL_DEST}/${UPDATE_FILE_DATA}"

	echo >"$INSTALL_DEST/${UPDATE_FILE_BIN}"
	if [[ -e "file_list_${ARCHITECTURE}.txt" ]]; then
		uninstall_file_list "file_list_${ARCHITECTURE}.txt" .
		rm -f "file_list_${ARCHITECTURE}.txt"
	fi
	rm -f "${INSTALL_DEST}/${UPDATE_FILE_BIN}"

	cd ~
	rm -d "${INSTALL_DEST}" 2>/dev/null || true

	if [[ -L "${BIN_DEST}/dockingstation" ]]; then
		rm -f "${BIN_DEST}/dockingstation"
	fi	
}

function user_launch()
{
	if [[ ! -z "${XDG_CONFIG_HOME}" ]]; then
		DS_HOME="${DS_HOME:-${XDG_CONFIG_HOME}/dockingstation}"
	else
		DS_HOME="${DS_HOME:-${HOME}/.config/dockingstation}"
	fi
	DS_MAIN="${INSTALL_DEST}"

	for X in Backgrounds Body\ Data Bootstrap Catalogue Creature\ Galleries Genetics Images Journal My\ Agents My\ Creatures My\ Worlds Overlay\ Data Sounds Users; do
		mkdir -p "${DS_HOME}/${X}"
	done
	cd "$DS_HOME"

	if [[ -d "${C3_MAIN}" ]]; then
		echo "Creatures 3 found at '${C3_MAIN}'."
		C3_INSTALLED=true
	else
		echo ""
		echo "Creatures 3 is not installed. You should buy and install it."
		echo ""
		C3_INSTALLED=
	fi

	if [[ -e "machine.cfg" ]]; then
		if ! grep "Everything Dummy" machine.cfg >/dev/null; then
			if [[ -z "$C3_INSTALLED" ]]; then
				echo "Creatures 3 has been removed since last launch."
				rm machine.cfg
			fi
		elif [[ ! -z "$C3_INSTALLED" ]]; then
			echo "Creatures 3 has been installed since last launch."
			rm machine.cfg
		fi
	fi
	if [[ -e "machine.cfg" ]]; then
		if ! grep "Main Auxiliary" machine.cfg >/dev/null; then
			echo "Updating configuration."
			rm machine.cfg
		fi
	fi

	if [[ ! -e "machine.cfg" ]]; then
		echo "Configuring game directories."
		echo "\"Game Name\" \"Docking Station\"" > machine.cfg
		cat >>machine.cfg <<END
"Backgrounds Directory" "${DS_MAIN}/Backgrounds/"
"Body Data Directory" "${DS_MAIN}/Body Data/"
"Bootstrap Directory" "${DS_MAIN}/Bootstrap/"
"Catalogue Directory" "${DS_MAIN}/Catalogue/"
"Creature Database Directory" "${DS_MAIN}/Creature Galleries/"
"Exported Creatures Directory" "${DS_MAIN}/My Creatures/"
"Genetics Directory" "${DS_MAIN}/Genetics/"
"Images Directory" "${DS_MAIN}/Images/"
"Journal Directory" "${DS_MAIN}/Journal/"
"Main Directory" "${DS_MAIN}/"
"Overlay Data Directory" "${DS_MAIN}/Overlay Data/"
"Resource Files Directory" "${DS_MAIN}/My Agents/"
"Sounds Directory" "${DS_MAIN}/Sounds/"
"Users Directory" "${DS_MAIN}/Users/"
"Worlds Directory" "${DS_MAIN}/My Worlds/"
END
		cat >>machine.cfg <<END
"Auxiliary 2 Backgrounds Directory" "${DS_HOME}/Backgrounds/"
"Auxiliary 2 Body Data Directory" "${DS_HOME}/Body Data/"
"Auxiliary 2 Bootstrap Directory" "${DS_HOME}/Bootstrap/"
"Auxiliary 2 Catalogue Directory" "${DS_HOME}/Catalogue/"
"Auxiliary 2 Creature Database Directory" "${DS_HOME}/Creature Galleries/"
"Auxiliary 2 Exported Creatures Directory" "${DS_HOME}/My Creatures/"
"Auxiliary 2 Genetics Directory" "${DS_HOME}/Genetics/"
"Auxiliary 2 Images Directory" "${DS_HOME}/Images/"
"Auxiliary 2 Journal Directory" "${DS_HOME}/Journal/"
"Auxiliary 2 Main Directory" "${DS_HOME}/"
"Auxiliary 2 Overlay Data Directory" "${DS_HOME}/Overlay Data/"
"Auxiliary 2 Resource Files Directory" "${DS_HOME}/My Agents/"
"Auxiliary 2 Sounds Directory" "${DS_HOME}/Sounds/"
"Auxiliary 2 Users Directory" "${DS_HOME}/Users/"
"Auxiliary 2 Worlds Directory" "${DS_HOME}/My Worlds/"
"Main Auxiliary" 2
END
		if [[ ! -z "${C3_INSTALLED}" ]]; then
			if [[ -d "Everything Dummy" ]]; then rm -d "Everything Dummy" || true; fi
			cat >>machine.cfg <<END
"Auxiliary 1 Backgrounds Directory" "${C3_MAIN}/Backgrounds/"
"Auxiliary 1 Body Data Directory" "${C3_MAIN}/Body Data/"
"Auxiliary 1 Bootstrap Directory" "${C3_MAIN}/Bootstrap/"
"Auxiliary 1 Catalogue Directory" "${C3_MAIN}/Catalogue/"
"Auxiliary 1 Creature Database Directory" "${C3_MAIN}/Creature Galleries/"
"Auxiliary 1 Exported Creatures Directory" "${C3_MAIN}/My Creatures/"
"Auxiliary 1 Genetics Directory" "${C3_MAIN}/Genetics/"
"Auxiliary 1 Images Directory" "${C3_MAIN}/Images/"
"Auxiliary 1 Journal Directory" "${C3_MAIN}/Journal/"
"Auxiliary 1 Main Directory" "${C3_MAIN}/"
"Auxiliary 1 Overlay Data Directory" "${C3_MAIN}/Overlay Data/"
"Auxiliary 1 Resource Files Directory" "${C3_MAIN}/My Agents/"
"Auxiliary 1 Sounds Directory" "${C3_MAIN}/Sounds/"
"Auxiliary 1 Users Directory" "${C3_MAIN}/Users/"
"Auxiliary 1 Worlds Directory" "${C3_MAIN}/My Worlds/"
END
		else
			mkdir -p "Everything Dummy"
			cat >>machine.cfg <<END
"Auxiliary 1 Backgrounds Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Body Data Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Bootstrap Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Catalogue Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Creature Database Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Exported Creatures Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Genetics Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Images Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Journal Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Main Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Overlay Data Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Resource Files Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Sounds Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Users Directory" "${DS_HOME}/Everything Dummy"
"Auxiliary 1 Worlds Directory" "${DS_HOME}/Everything Dummy"
END
		fi
	fi

	if [[ ! -e "language.cfg" ]]; then
		echo "Language en-GB" >language.cfg
		echo "LanguageCLibrary english-uk" >>language.cfg
	fi
	if [[ ! -e "server.cfg" && -e "${DS_MAIN}/server.cfg" ]]; then
		cat "${DS_MAIN}/server.cfg" | tr -d "\r" >server.cfg
	fi
	if [[ ! -e "user.cfg" && -e "${DS_MAIN}/user.cfg" ]]; then
		cat "${DS_MAIN}/user.cfg" | tr -d "\r" | sed 's/DS_/ds_/' >user.cfg
		echo "Icon \"${DS_MAIN}/dstation.bmp\"" >>user.cfg
	fi

	if [[ ! -e "${DS_HOME}/Bootstrap/000 Switcher" ]]; then
		ln -sf "${DS_MAIN}/Bootstrap/000 Switcher" "${DS_HOME}/Bootstrap"
	fi
	if [[ ! -e "${DS_HOME}/lc2e-netbabel.so" ]]; then
		ln -sf "${DS_MAIN}/lc2e-netbabel.so" "${DS_HOME}/lc2e-netbabel.so"
	fi

	echo "Welcome to Docking Station!"
	export LD_LIBRARY_PATH="$DS_MAIN:$LD_LIBRARY_PATH"
	"${DS_MAIN}/lc2e" --autokill
}

# == Check Arguments ==

for PARAM in ${SELF_PARAMETERS}; do
	if [[ "${PARAM}" == "uninstall" ]]; then
		uninstall
		exit 0
	elif [[ "${PARAM}" == "lang" ]]; then
		rm -f ~/.dockingstation/language.cfg
	elif [[ "${PARAM}" == "cleanse" ]]; then
		check_writeable "${INSTALL_DEST}"
		echo >"${INSTALL_DEST}/${UPDATE_FILE_BIN}"
		echo >"${INSTALL_DEST}/${UPDATE_FILE_DATA}"
	elif [[ "${PARAM}" == "nocheck" ]]; then
		NO_CHECK=true
	elif [[ "${PARAM}" = "nolaunch" ]]; then
		NO_LAUNCH=true
	elif [[ "${PARAM}" != "" ]]; then
		echo
		echo "Docking Station"
		echo "---------------"
		echo
		echo "To download and run the game, simply run this script with no"
		echo "parameters. You do not need to run the script as root."
		echo 	
		echo "When the download is complete the game will automatically launch."
		echo "Next time, type \'dockingstation\' to check for updates and launch"
		echo "the game."
		echo
		echo "Supported Arguments:"
		echo "  lang - Change game language."
		echo "  cleanse - Rescan installed files."
		echo "  nocheck - Skip update check."
		echo "  nolaunch - Skip game launch."
		echo "  uninstall - Uninstall game files."
		echo
		echo "Supported Environment Variables:"
		echo "  INSTALL_DEST - Game Files Destination"
		echo "  BIN_DEST - Binary Symlink Destination"
		echo "  C3_MAIN - Creatures 3 Location"
		exit 1
	fi
done

if [[ ! -z "${CD_PATH}" || ! -z "${DOWNLOAD_MIRROR}" ]]; then
	[ -z "$NO_CHECK" ] && update
fi
if [[ $EUID != 0 ]]; then
	[ -z "$NO_LAUNCH" ] && user_launch
fi
exit 0
