#!/bin/bash
set -euf -o pipefail

# SYS Hosts
SYSHOSTS=("mars.cs.tu-dortmund.de")

# SSH Key
SYSSSHKEY="$HOME/.ssh/stubs"

# Welcome message
echo -e "\n\e[1;4mStuBS Development Environment Setup\e[0m\n"

# Check tools
function toolreq(){
	if ! command -v $1 &> /dev/null ; then
		echo -e "\e[31m$1 not found!\e[0m"
		echo "$2 is required for developing StuBS - please install it!"
		echo
		exit 1
	fi
}

function toolsug(){
	if ! command -v $1 &> /dev/null ; then
		echo -e "\e[33m$1 not found\e[0m"
		echo "$2 is recommended for developing StuBS."
		echo
	fi
}

toolreq git "Git"
toolreq g++ "GCC/g++"
toolreq make "GNU Make"
toolreq nasm "Netwide Assembler"
toolreq qemu-system-x86_64 "Qemu (x86_64)"
toolsug gdb "GNU Debugger"
toolsug python3 "Python (for cpplint)"

# Check KVM
if ! grep -q '\slm\s' /proc/cpuinfo ; then
	echo -e "\e[33mYour CPU might not support x64...\e[0m"
elif ! grep -q 'vmx\|svm\|0xc0f' /proc/cpuinfo ; then
	echo -e "\e[33mYour CPU might not support hardware virtualization (KVM)...\e[0m"
elif grep -q kvm /etc/group && ! groups | grep kvm >/dev/null ; then
	echo -e "\e[33mYour user is not member of the group 'kvm'\e[0m"
	echo "You probably need to run"
	echo "	sudo adduser $USER kvm"
	echo "or"
	echo "	sudo gpasswd -a $USER kvm"
	echo "or"
	echo "	sudo usermod -a -G kvm $USER"
	echo "to be able to use hardware virtualization in Qemu"
	echo
elif ! /sbin/modprobe -c | grep "options kvm vector_hashing=[Nn0]" ; then
	echo -e "\e[33mKVM vector hashing might be active...\e[0m"
	echo "Active vector hashing will prevent the desired rotation of CPUs in interrupt handling."
	echo "Further details at https://www4.cs.fau.de/Lehre/WS20/V_BS/Uebungen/faq.shtml"
	echo
fi

# Read SYS account
echo "You'll need a valid SYS student account."
echo "If not available, contact sys-admins@ls12.cs.tu-dortmund.de"
user=""
while true ; do
	read -p "Enter your SYS student account: " user
	echo
	if [[ $user =~ ^[a-z]{2}[0-9]{2}[a-z]{4}|s[a-z0-9]{7}|heinloth|eichler|vrsieh$ ]] ; then
		break
	else
		echo -e "\e[31mInvalid user name!\e[0m"
	fi
done

# Generate SSH key
mkdir -p $(dirname $SYSSSHKEY)
if [[ ! -f $SYSSSHKEY ]] ; then
	echo -e "\n\e[1mCreating new SSH key...\e[0m"
	ssh-keygen -f $SYSSSHKEY -N ""
fi

# Check hosts
echo -e "\n\e[1mFinding online host...\e[0m"
for host in $(shuf -e "${SYSHOSTS[@]}" ); do
	# Online?
	if timeout 11 ping -c1 -W3 $host >/dev/null 2>&1 ; then

		# Copy SSH key
		echo -e "\n\e[1mCopying SSH key to host $host...\e[0m"
		ssh-copy-id -i $SYSSSHKEY -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $user@$host

		# Generate config
		if [[ ! -f "$HOME/.ssh/config" ]] || ! grep -q "Host mars.cs.tu-dortmund.de" ~/.ssh/config ; then
			echo -e "\n\e[1mGenerating SSH config...\e[0m"
			echo "Host mars.cs.tu-dortmund.de
    User $user
    IdentityFile $SYSSSHKEY
    ConnectTimeout 5
    Protocol 2
    HashKnownHosts no
    UserKnownHostsFile=/dev/null
    StrictHostKeyChecking=no
    TCPKeepAlive yes" >> $HOME/.ssh/config

			# Enable Multiplexing
			read -p "Should SSH use multiplexing (y/n)? " -n 1 -r
			echo
			if [[ $REPLY =~ ^[Yy]$ ]] ; then
				echo -e "\n\e[1mEnabling multiplexing...\e[0m"
				mkdir -p "$HOME/.ssh/controlmasters/"
				echo "    ControlPath ~/.ssh/controlmasters/%C
    ControlMaster auto
    ControlPersist 10m
    ServerAliveInterval 10" >> $HOME/.ssh/config
			fi
			echo >> $HOME/.ssh/config
		fi

		# Test Settings
		ssh -t $host "figlet \"It's working\" | lolcat"

		# Gitlab
		echo -e "\n\e[1mYour key:\e[0m\n---------"
		cat $SYSSSHKEY.pub
		echo -e "---------\n\e[3mPlease paste it in https://git.cs.tu-dortmund.de/user/settings/keys\e[0m"
		if cat $SYSSSHKEY.pub | xclip -selection c ; then
			echo -e "\e[3m(copied into clipboard)\e[0m"
		fi

		# Exit
		exit 0
	fi
done

# Error
echo -e "\e[31mNo host reachable - faulty network connection?\e[0m"
exit 1
