#!/bin/bash

# system-setup has been split into scripts under /etc/scripts/system-setup.d
# the purpose is to have different skel areas contribute different scripts into
# the system-setup stage

# set null globbing, we need this for our scripts
shopt -s nullglob

# sourcing our /etc/rear/local.conf file as we need some variables
. /etc/rear/local.conf
[[ -f /etc/rear/rescue.conf ]] && . /etc/rear/rescue.conf

function debug() {
	read -r </proc/cmdline
	case "$REPLY" in
		(*debug*) return 0 ;;
		(*) return 1;;
	esac
}

if debug ; then
	echo "---> DEBUG MODE ENABLED, starting shell on tty9 <---"
	echo
	/bin/bash </dev/tty9 >/dev/tty9 2>&1 &
fi

echo "* * * Configuring Rescue System * * *"
for s in /etc/scripts/system-setup.d/*.sh ; do
	if debug ; then
		read -p "Press ENTER to run $(basename $s) "
		set -x
	else
		echo "Running $(basename $s)..."
	fi
	source $s
	set +x
done
echo "* * * Rescue System is ready * * *"

# Launch rear recover automatically
if grep -q 'auto_recover' /proc/cmdline ; then
        rear recover -v
        
	choices=(
	    "View Relax-and-Recover log"
	    "Go to Relax-and-Recover shell"
	)
	if [ $? -eq 0 ] ; then
	    choices=(
	    "${choices[@]}"
	    "Reboot"
	    )
	    echo -e "\n\n Success !\n"
	else
	    echo -e "\n\n Errors, please see log file !\n"
	fi

	PS3="What do you want to do now ? "
	select choice in "${choices[@]}"; do
	    case "$REPLY" in
		(1) less /var/log/rear/rear-$HOSTNAME.log;;
		(2) echo "" > /etc/issue
		    echo "" > /etc/motd
		    break;;
		(3) reboot;;
	    esac
	    for (( i=1; i <= ${#choices[@]}; i++ )); do
		echo "$i) ${choices[$i-1]}"
	    done
	done 2>&1
fi
