#!/bin/bash

myNic="$(ls /sys/class/net/ -1 | grep -v lo | grep -v wlan)"

if [ -e /root/reboot ]; then
	rm /root/reboot
	touch /root/join
	systemctl reboot
	exit 0
fi


if [ -e /root/cluster ]; then
	clusterJoin="$(cat /root/cluster)"
fi


if [ -e /root/join ]; then
	# Stop the display manager to output on tty7
	systemctl stop lightdm
	# Change root password
	if [ -e /root/new_root_pw ] ; then
		echo "root:$(cat /root/new_root_pw)" | chpasswd -e
	fi
	# Following dhclient was necessary inside a virtual(box) environment. Not sure if needed anymore. In case it can be removed or commented.    
	dhclient $myNic
	screen -d -m -S XY
	screen -S XY -X stuff "exec 2>&1 > /dev/tty7\n"
	screen -S XY -X stuff "fuss-client -av $clusterJoin && rm /root/join ; reboot\n"
else
        rm /etc/rc.local
	rm /root/clientScript
	rm -fr /root/.ssh/id_rsa*
	rm /root/.ssh/known_hosts
	sed -i '/clonezilla/d' /root/.ssh/authorized_keys
	rm /root/cluster
fi

