#! /bin/sh
#
# bootstrap.sh
# Copyright (C) 2020 Vintage Salt <rehashedsalt@cock.li>
#
# Distributed under terms of the MIT license.
#

set -e

if [ "$(id -u)" != "0" ]; then
	echo "This script must be run as root"
	exit 1
fi

if ! [ -f "./desu.pub" ]; then
	echo "The public key \"desu.pub\" must sit in PWD. cd to contrib"
	exit 2
fi

echo "Adding ansible user..."

if ! \
	useradd \
		-K UID_MIN=600 \
		-K UID_MAX=700 \
		-K GID_MIN=600 \
		-K GID_MAX=700 \
		ansible \
		> /dev/null 2>&1
	then
	err=$?
	case $err in
		0)
			;;
		9)
			echo "Continuing..."
			;;
		*)
			echo "Encountered error $err adding user ansible"
			exit 3
			;;
	esac
fi

echo "Adding key..."

mkdir -p ~ansible/.ssh
cat ./desu.pub > ~ansible/.ssh/authorized_keys

echo "Fixing perms..."

chmod 0600 ~ansible/.ssh/authorized_keys
chown -R ansible. ~ansible/.ssh
cat > /etc/sudoers.d/50-ansible << EOF
ansible	ALL=(ALL:ALL) NOPASSWD:ALL
EOF

echo "Done!"