#!/bin/bash
DOMAIN=${DOMAIN:-code.secondbit.org}
SSH_KEYS_BUCKET=${SSH_KEYS_BUCKET:-sshkeys.$DOMAIN}
SSH_HOST_KEYS_BUCKET=${SSH_HOST_KEYS_BUCKET:-hostkeys.$DOMAIN}

mkdir -p /tmp/sshkeys
mkdir -p /tmp/hostkeys

echo "Cleaning up..."
rm -rf /tmp/sshkeys/*
rm -rf /tmp/hostkeys/*

echo "Downloading keys from gs://${SSH_KEYS_BUCKET}/"

output=$(gsutil cp -R gs://$SSH_KEYS_BUCKET/\* /tmp/sshkeys/ 2>&1)
echo $output

keys=$(find /tmp/sshkeys -name '*.pub')

for key in $keys
do
	dir=$(dirname $key)
	stripped=${dir#.}
	stripped=${stripped#/tmp/sshkeys}
	target=${key#/tmp/sshkeys}
	target=${target%.pub}
	target=${target#/}
	IFS='-' read -ra USERSPEC <<< $target
	if [ -d "/home${USERSPEC[0]}" ]
	then
		echo "User ${USERSPEC[0]} already exists, skipping."
	else
		echo "Creating user ${USERSPEC[0]} with ID ${USERSPEC[1]}."
		/bin/bash /usr/local/bin/helpers/create_user.sh "${USERSPEC[0]}" "${USERSPEC[1]}"
		cat $key > /home/${USERSPEC[0]}/.ssh/authorized_keys
	fi
done

echo "Downloading host keys from gs://${SSH_HOST_KEYS_BUCKET}/"

output=$(gsutil cp -R gs://$SSH_HOST_KEYS_BUCKET/\* /tmp/hostkeys/ 2>&1)
echo $output

keys=/tmp/hostkeys/*

for key in $keys
do
	if [[ $key != *".pub" ]]
	then
		chmod 0700 $key
	fi
	target="/etc/ssh/${key##*/}"
	echo "Moving $key to $target"
	rm $target
	mv $key $target
done

echo "Cleaning up..."
rm -rf /tmp/sshkeys/*
rm -rf /tmp/hostkeys/*

echo "SSH key pull complete."
