#!/bin/sh

# ---------------------
# Define variable WITH_HAVEGED iff you like to
# use random source haveged.
#   WITH_HAVEGED="defined"
# Otherwise, define the variable as empty string.
#   WITH_HAVEGED=""

#WITH_HAVEGED=""
WITH_HAVEGED="defined"

#For ANSI colors
# eg. described in https://www.linuxjournal.com/article/8603
ESC=""
NORMAL="${ESC}[0;39m"
BLACK="${ESC}[1;30m"
# RED: Failure or error message
RED="${ESC}[1;31m"
# GREEN: Success message
GREEN="${ESC}[1;32m"
# YELLOW: Descriptions
YELLOW="${ESC}[1;33m"
# BLUE: System messages
BLUE="${ESC}[1;34m"
BLUE_EMPHASIZED="${ESC}[5;34m"
# MAGENTA: Found devices or drivers
MAGENTA="${ESC}[1;35m"
# CYAN: Questions
CYAN="${ESC}[1;36m"
# BOLD WHITE: Hint
WHITE="${ESC}[1;37m"

echo "${BLUE}Starting linuxrc${NORMAL}"

# Suppress kernel and modules messages (except panic) from appearing on the console
dmesg -n 1

#For UEFI
mount -o remount,rw /dev/ram0 /

#kernel=`uname -r`
#find /lib/modules/$kernel -type f | grep atl1c.ko | xargs rm

/bin/HWMiniInit.sh
/etc/init.d/m23hwdetect

touch /var/run/utmp

for i in $( seq 0 9 )
do
	ifconfig eth$i 1.1.1.$i > /dev/null 2>&1
done

#Show the MAC adress(es)
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo "MAC addresses"
ifconfig | grep eth
echo "Press Ctrl+C if the output is too fast"
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"

ln -s /bin/dhclient-script /sbin/dhclient-script

#Configure via DHCP
dhclient-script

# FABR: mute error channel of dhclient
# The binary makes a call to chmod with some option that is not supported by
# chmod code built into busybox.

dhclient > /dev/null 2>&1

#Stop dhclient to make sure that the IP configuration will not be changed during installation
for dhClientPID in `ps | grep dhclient | tr -s [:blank:] | cut -d' ' -f2`
do
	kill -9 $dhClientPID > /dev/null 2>&1
done

killall -9 dhclient  > /dev/null 2>&1

if [ -z $WITH_HAVEGED ]
then
#Configure random as non blocking random
	mv /dev/random /dev/random-blocks
	ln -s /dev/urandom /dev/random
else
	# Prepare usage of haveged
rm /dev/random
mknod -m 444 /dev/random c 1 9
fi

for i in `seq 1 9`
do
	mknod /dev/vda$i b 254 $i
done







I18N_windowheader="m23 client - Manual network setup"



showDialog()
{
	echo "dialog --backtitle `echo \"'$1'\"` --title `echo \"'$2'\"` --clear --$3 `echo \"'$6'\"` $4 $5 "$8" 2> /tmp/dialog.value; exit \$?" > /tmp/dialog.cmd

	sh /tmp/dialog.cmd

	ret=$?

	#analyse the return code only if $7 isn't set
	if test "$7" = "disable"
	then
		case $ret in
			1 | 255)
				dialog --backtitle "$I18N_windowheader" --title "$I18N_windowheader" --clear --msgbox "$I18N_cancelinstallation" 12 41
				exit;;
		esac
	fi

	return $ret
}



showNetworkDialog()
{
	showDialog "$I18N_windowheader" "No IP obtained" msgbox 7 61 "No IP address could be obtained from the m23 DHCP server.

Please hit Enter and provide the needed information."


	# enter IP
	showDialog "$I18N_windowheader" "IP address" inputbox 10 51 "Enter the IP of this m23 client."
	ip=`cat /tmp/dialog.value`

	# enter subnetmask
	showDialog "$I18N_windowheader" "Network mask" inputbox 10 51 "Enter the networkmask of this m23 client." notDisabled `ipcalc -m $ip | cut -d'=' -f2`
	submask=`cat /tmp/dialog.value`
	ifconfig eth0 $ip netmask $submask

	# enter gateway
	showDialog "$I18N_windowheader" "Gateway IP" inputbox 10 51 "Enter the gateway IP to connect to the internet."
	gateway=`cat /tmp/dialog.value`
	route add -net default gw $gateway

	# enter nameserver
	showDialog "$I18N_windowheader" "Nameserver IP" inputbox 10 51 "Enter the IP of a DNS server." notDisabled "85.88.19.10"
	nameserver=`cat /tmp/dialog.value`	
	echo "nameserver $nameserver" > /etc/resolv.conf

	# enter gateway
	showDialog "$I18N_windowheader" "IP of the m23 server" inputbox 10 51 "Enter the IP of the m23 server."
	server=`cat /tmp/dialog.value`
}





#Fetch the public SSH key of the m23 server and start dropbear
startDropbear()
{
	mkdir -p /root/.ssh
	chmod 700 /root/.ssh

	echo ""
	echo "${MAGENTA}wget -T2 -qq -O - http://$server/packages/baseSys/authorized_keys${NORMAL}"
	wget -T2 -qq -O - http://$server/packages/baseSys/authorized_keys >> /root/.ssh/authorized_keys

	if [ -f /root/.ssh/authorized_keys ]
	then
		echo "${GREEN}INFO: Successfully copied authorized_keys from the m23 server${NORMAL}"
		chmod 700 /root/.ssh/authorized_keys
		chown root /root/.ssh/authorized_keys
		chgrp root /root/.ssh/authorized_keys
	else
		echo "${RED}ERROR: unable to wget /root/.ssh/authorized_keys from m23 server${NORMAL}"
	fi
	echo ""

	mkdir -p /etc/dropbear

	dropbearkey -type rsa -f /etc/dropbear/dropbear_rsa_host_key
	dropbearkey -type dss -f /etc/dropbear/dropbear_dss_host_key

	cp -r /root/.ssh /
	chmod 700 /.ssh /tmp /
	chown root /.ssh /
	dropbear
}





#Checks, if there is another m23 server (another than the DHCP server)
checkAlternativeM23Server()
{
	touch /m23clientIDAdd

	#wget -qq "http://$1/latest/availability-zone" -O /dev/null
	wget -qq -T2 -t1 "http://$GATEINT/latest/public-ipv4" -O /tmp/csExternIp

	if [ $? -eq 0 ] && [ -f /tmp/csExternIp ] && [ $(grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' -c /tmp/csExternIp) -eq 1 ]
	then
		wget -qq  -T2 -t5 "http://$1/latest/user-data" -O /tmp/CSud
		echo -n "?m23clientID=`hostname`" > /m23clientIDAdd
		hostname > /m23clientID
		grep m23server /tmp/CSud | cut -d'=' -f2
	else
		echo -n "$1"
	fi
	rm /tmp/csExternIp 2> /dev/null
}





if [ $m23server ]
then
	server=$m23server

	#Check if the hostname is a valid m23shared client ID
	if [ `hostname | grep -c "^m23S"` -gt 0 ]
	then
		m23Client="?m23clientID=`hostname`"
		echo `hostname` > /m23clientID
	else
		#Check if the ID of the m23 client was choosen by the m23clientID kernel parameter.
		if [ $m23clientID ]
		then
			id=$m23clientID
		else
			repeat=true

			#Repeat reading the client name until a valid name is entered
			while $repeat
			do
				dialog --backtitle "m23@web" --title "Clientname" --clear --inputbox "Please enter the complete m23 client ID of this client:
Bitte geben Sie die komplette m23-Client-Nummer dieses Rechners ein:" 10 75 m23S 2> /tmp/m23sClName

				ret=$?
	
				#Check if the return code of dialog is ok, the clien name begins with the keyword and has a dot.
				if [ $ret -eq 0 ] && [ `grep -c ^m23S /tmp/m23sClName` -eq 1 ] && [ `grep -c '\.' /tmp/m23sClName` -eq 1 ]
				then
					repeat=false
				fi
			done

			id=`cat /tmp/m23sClName`
		fi

		m23Client="?m23clientID=$id"
		echo $id > /m23clientID
	fi
else
	#Get the server via DHCP log
	for i in `grep dhcp-server-identifier /var/lib/dhcp/dhclient.leases | cut -d' ' -f5 | cut -d';' -f1`
	do
# 		server=$(checkAlternativeM23Server "$i")
		server="$i"
		m23Client=$( cat /m23clientIDAdd )
	done
fi

#----------------------
# Debug
#----------------------
echo "${GREEN}"
echo "DEBUG INFO:"
echo "Client/Server parameters:"
echo "server=$server"
echo "m23Client=$m23Client"
echo "${NORMAL}"

if [ -z $server ]
then
	showNetworkDialog
fi

#--------------------
# Use alternative random source: haveged
# 

if [ ! -z $WITH_HAVEGED ]
then
haveged
fi

echo ""
echo "${CYAN}"   
echo "(Pseudo-)Random number generator is warming up..."
echo "This may cause a delay of several minutes. Please be patient."
echo ""
echo "You may speed-up the initialization process if you press"
echo "the SHIFT-key on the client's keyboard until you see the message"
echo "${WHITE}     random: crng init done${CYAN}"
echo "${NORMAL}"

#--------------------
# Activate ssh server

startDropbear

#------------------------------------------------
#Try to download the first job and debug commands
#--
# Note:
# If we download pages via SSL, we do not check the SSL certicicate of the server.
# Option: --no-check-certificate
#
# CAVEAT: 
# Using SSL requires an initialized random number generator in the kernel.
# Creating some entropy via keyboard activity shortens the waiting time.

# Download debug commands
echo "${MAGENTA}wget -T600 -t2 -qq http://$server/debugScreen.php$m23Client -O debug.sh${NORMAL}"
wget -T600 -t2 -qq http://$server/debugScreen.php$m23Client -O debug.sh

# Download the first job
# Use SSL to make sure that the random generator is initialized
# for later phases of the auto-installation.
echo "${MAGENTA}wget -T600 -t2 -qq --no-check-certificate https://$server/work.php$m23Client -O work.php${NORMAL}"
wget -T600 -t2 -qq --no-check-certificate https://$server/work.php$m23Client -O work.php
#echo "${MAGENTA}wget -T600 -t2 -qq --no-check-certificate https://$server/work.php$m23Client -O work.php${NORMAL}"
#wget -T600 -t2 -qq http://$server/work.php$m23Client -O work.php

#########DEBUG##########

# Check, if the work.php contains the required shebang in the first 5 lines: "#!/bin/bash"
if [ $(head -5 work.php 2>/dev/null | grep -c '/bin/bash') -eq 0 ]
then
	echo ""
	echo "${RED}FATAL ERROR${NORMAL}"
	echo "${RED}work.php does NOT contain expected shebang${NORMAL}"
	echo ""
	exit 1
else
	echo ""
	echo "${GREEN}work.php contains expected shebang${NORMAL}"
        sleep 5
#	echo "EXIT DEBUG"
#	exit 0
fi

startDropbear

# Execute debug commands
chmod +x debug.sh
./debug.sh

# Make work.php executable
chmod +x work.php

# Run work.php in screen
export SCREENRC="/etc/screenrc"
script /dev/null -c "screen -mS m23install ./work.php"
