#!/bin/bash
trap "" 0 1 2 5 15

export IVERSION="4.5"
export IBUILD="20251231"
export CTOOLNAME="CRANIX Clone Tool ${IVERSION}"

mkdir -p /mnt/itool
umount /mnt/itool > /dev/null 2>&1
rm -Rf /tmp/* > /dev/null 2>&1

chmod 700 /root/.ssh/
chmod 600 /root/.ssh/authorized_keys

WARNING='Anmeldung am System war nicht moeglich!\n\n
Dies koennte mehrere Gruende haben.\n\n
 - Falscher Benutzername\n
 - Falsches Passwort\n
 - Fehlerhafte Konfiguration des Server\n
 - Keine Verbindung zum Server\n\n\n
Moechten Sie es erneut versuchen?'

## Check for some boot parameter
if [ -z "${ITOOL}" ]
then
        export ITOOL="partclone"
fi
## Check for some boot parameter
if [ -z "${STARTCMD}" ]
then
        export STARTCMD="clone"
fi
## Check for some boot parameter
if [ -z "${SERVER}" ]
then
        export SERVER="admin"
fi

if [ -z "${SLEEP}" ]
then
        export SLEEP=1
fi

loadkeys de-latin1

curl ftp://${SERVER}/itool/scripts/login-functions.sh > /root/login-functions.sh
source /root/login-functions.sh &> /dev/null || {
	echo "ERROR SERVER IS NOT AVAILABLE"
	echo "Fehler Server nicht erreichbar"
	sleep 10
	exit 1
}

if [ "$MODUS" = "AUTO" ]
then
	auto_login
else
	authorization
	source /tmp/apiparams
	if [ -z "${HOSTNAME}" ]; then
		register
	fi
	/bin/bash ${CDEBUG} /root/${STARTCMD}.sh
	curl --insecure -X DELETE --header 'Content-Type: application/json' --header 'Accept: application/json' --header "Authorization: Bearer $TOKEN" "https://${SERVER}/api/sessions/$TOKEN"
	exit 0
fi
