#!/bin/sh

set -eu

CONFIG_DIR="${CONFIG_DIR:-/etc/geordi}"

. /usr/share/geordi/_functions
. /etc/geordi/scripts-config

trap 'cd "$(pwd)"' EXIT

RT=${RT:-"/var/lib/geordi/rt"}
AUTO_RECONNECT="${AUTO_RECONNECT:-0}"
ALWAYS_REFRESH_CHROOT="${ALWAYS_REFRESH_CHROOT:-1}"
DEBUG=${DEBUG:-0}
INFO=${INFO:-1}

SIMPLE_RECONNECT=0

cd "${CONFIG_DIR}"

Refresh_chroot () {
	if [ ${SIMPLE_RECONNECT} -eq 1 ]
	then
		SIMPLE_RECONNECT=0
		return
	fi

	Cond_refresh_chroot
}

Connect () {
	Refresh_chroot

	Echo_debug "Starting geordi"

	Test_chroot

	/usr/lib/geordi/geordi-irc -c "${CONFIG_DIR}/irc-config"
	STATUS=$?
	Echo_debug "Geordi exited with exit status ${STATUS}"
	
	return ${STATUS}
}

TIMEOUT=5
MAX_TIMEOUT=120
Auto_reconnect() {
	while true
	do
		Connect || STATUS=$?

		Echo_debug "Auto-reconnecting Geordi exited with exit status ${STATUS}"

		case ${STATUS} in
			252)
				Echo_info "Auto-reconnection cancelled."
				exit ${STATUS}
				;;
			143)
				Echo_info "Geordi killed - reconnecting."
				TIMEOUT=0
				Refresh_chroot
				;;
			*)
				# Don't refresh chroot when simply reconnecting
				SIMPLE_RECONNECT=1
				;;
		esac

		if [ ${TIMEOUT} -gt ${MAX_TIMEOUT} ]
		then
			TIMEOUT=${MAX_TIMEOUT}
		fi

		Echo_info "Waiting for ${TIMEOUT} seconds before reconnecting"
		sleep ${TIMEOUT}

		TIMEOUT=$((${TIMEOUT} * 2))
	done
}

if Is_true ${AUTO_RECONNECT}
then
	Auto_reconnect
else
	Connect
fi
