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

mkdir -p /tmp/sshkeys

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

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 "Cleaning up..."
rm -rf /tmp/sshkeys/*

echo "SSH key pull complete."
