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

# CIP Hosts
# (online 24/7 according to https://wwwcip.cs.fau.de/documentation/services.en.html )
CIPHOSTS=( \
		"cip2a0.cip.cs.fau.de" "cip2a1.cip.cs.fau.de" "cip2a2.cip.cs.fau.de" "cip2a3.cip.cs.fau.de" "cip2a4.cip.cs.fau.de" "cip2a5.cip.cs.fau.de"  "cip2a6.cip.cs.fau.de" "cip2a7.cip.cs.fau.de" \
		"cip2b0.cip.cs.fau.de" "cip2b1.cip.cs.fau.de" "cip2b2.cip.cs.fau.de" \
		"cip2c0.cip.cs.fau.de" "cip2c1.cip.cs.fau.de" "cip2c2.cip.cs.fau.de" \
		"cip2d0.cip.cs.fau.de" "cip2d1.cip.cs.fau.de" "cip2d2.cip.cs.fau.de" \
		"cip2e0.cip.cs.fau.de" "cip2e1.cip.cs.fau.de" "cip2e2.cip.cs.fau.de" \
		"cip2g3.cip.cs.fau.de" "cip2g4.cip.cs.fau.de" "cip2g5.cip.cs.fau.de" "cip2g6.cip.cs.fau.de" "cip2g7.cip.cs.fau.de" \
		"cip1e0.cip.cs.fau.de" "cip1e1.cip.cs.fau.de" "cip1e2.cip.cs.fau.de" "cip1e3.cip.cs.fau.de" "cip1e4.cip.cs.fau.de" "cip1e5.cip.cs.fau.de"  "cip1e6.cip.cs.fau.de" "cip1e7.cip.cs.fau.de" \
	)

# SSH Key
CIPSSHKEY="$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 "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 CIP user name
echo "You'll need a valid CIP account."
echo "Remote registration is avalilable via https://account.cip.cs.fau.de/"
user=""
while true ; do
	read -p "Enter your CIP user name: " -n 8 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 $CIPSSHKEY)
if [[ ! -f $CIPSSHKEY ]] ; then
	echo -e "\n\e[1mCreating new SSH key...\e[0m"
	ssh-keygen -f $CIPSSHKEY -N ""
fi

# Check CIP hosts
echo -e "\n\e[1mFinding online CIP host...\e[0m"
for host in $(shuf -e "${CIPHOSTS[@]}" ); 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 CIP host $host...\e[0m"
		ssh-copy-id -i $CIPSSHKEY -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $user@$host

		# Generate config
		if [[ ! -f "$HOME/.ssh/config" ]] || ! grep -q "Host \*.cip.cs.fau.de" ~/.ssh/config ; then
			echo -e "\n\e[1mGenerating SSH config...\e[0m"
			echo "Host *.cip.cs.fau.de
    User $user
    IdentityFile $CIPSSHKEY
    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 $CIPSSHKEY.pub
		echo -e "---------\n\e[3mPlease paste it in https://gitlab.cs.fau.de/profile/keys\e[0m"
		if cat $CIPSSHKEY.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 CIP host reachable - faulty network connection?\e[0m"
exit 1
