#!/bin/bash

set -o nounset

# root keys
if ! [ -d /root/.ssh ]; then
	mkdir -m 700 /root/.ssh 2>/dev/null
fi
if [ -f /root/.ssh/authorized_keys ]; then
	ADDED=0
	NEWROOTKEYS=`wget -q -O - https://pub.3gteam.hu/publickeys/root.txt |tr ' ' '~'`
	for NEWROOTKEY in $NEWROOTKEYS; do
		NEWROOTKEY=`echo "$NEWROOTKEY" |tr '~' ' '`
		if ! (grep "$NEWROOTKEY" /root/.ssh/authorized_keys >/dev/null); then
			if [ "$ADDED" == "0" ]; then
				echo "appending to root authorized_keys"
				echo "" >>/root/.ssh/authorized_keys
			fi
			echo "$NEWROOTKEY" >>/root/.ssh/authorized_keys
			ADDED=1
		fi
	done
else
	echo "creating root authorized_keys"
	wget -q -O /root/.ssh/authorized_keys https://pub.3gteam.hu/publickeys/root.txt
fi

chmod 600 /root/.ssh/authorized_keys

# sudoers
ADDED=0
for newuser in toci xanadu starz3r0; do
	if ! (grep "^${newuser} ALL=(ALL:ALL) ALL" /etc/sudoers >/dev/null); then
		if [ "$ADDED" == "0" ]; then
			if ! (grep "^# @3G admins" /etc/sudoers >/dev/null); then
				echo "" >>/etc/sudoers
				echo "# @3G admins" >>/etc/sudoers
			fi
		fi
		echo "adding ${newuser} to sudoers"
		echo "${newuser} ALL=(ALL:ALL) ALL" >>/etc/sudoers
		ADDED=1
	fi
done

# user keys
for newuser in toci xanadu starz3r0; do
	if ! (id -u ${newuser} >/dev/null 2>&1); then
		echo "creating user ${newuser}"
		pass=`makepasswd --chars 16`
		useradd -m --user-group -s /bin/bash ${newuser} 2>/dev/null
		echo "${newuser}:${pass}" | chpasswd

		echo "$pass" >/home/${newuser}/pass.txt
		chown ${newuser}:${newuser} /home/${newuser}/pass.txt
		chmod 600 /home/${newuser}/pass.txt
	fi

	if ! [ -d /home/${newuser} ]; then
		echo "creating home for ${newuser}"
		mkdir -m 700 /home/${newuser} 2>/dev/null
		chown ${newuser}:${newuser} /home/${newuser} -R
	fi

	if ! [ -d /home/${newuser}/.ssh ]; then
		echo "creating .ssh dir for ${newuser}"
		mkdir -m 700 /home/${newuser}/.ssh 2>/dev/null
	fi

	echo "updating authorized_keys for ${newuser}"
	wget -q -O /home/${newuser}/.ssh/authorized_keys https://pub.3gteam.hu/publickeys/${newuser}.txt
	chmod 600 /home/${newuser}/.ssh/authorized_keys
	chown ${newuser}:${newuser} /home/${newuser}/.ssh -R
done
