#!/usr/bin/env bash
# Run once as root on a fresh server to create the deploy user Ansible connects as.
# Usage: bash bootstrap-deploy-user.sh <ssh-public-key>

set -euo pipefail

SSH_PUBKEY="${1:?Usage: bootstrap-deploy-user.sh <ssh-public-key>}"
DEPLOY_USER="deploy"

if [ "$(id -u)" -ne 0 ]; then
  echo "ERROR: must be run as root" >&2
  exit 1
fi

echo "==> Creating user '${DEPLOY_USER}'"
if id "${DEPLOY_USER}" &>/dev/null; then
  echo "    user already exists, skipping"
else
  adduser --disabled-password --gecos "" "${DEPLOY_USER}"
fi

echo "==> Adding '${DEPLOY_USER}' to sudo group"
usermod -aG sudo "${DEPLOY_USER}"

echo "==> Granting '${DEPLOY_USER}' passwordless sudo"
echo "${DEPLOY_USER} ALL=(ALL) NOPASSWD: ALL" > "/etc/sudoers.d/${DEPLOY_USER}"
chmod 440 "/etc/sudoers.d/${DEPLOY_USER}"

echo "==> Installing SSH authorized key"
SSH_DIR="/home/${DEPLOY_USER}/.ssh"
AUTH_KEYS="${SSH_DIR}/authorized_keys"
mkdir -p "${SSH_DIR}"
if grep -qF "${SSH_PUBKEY}" "${AUTH_KEYS}" 2>/dev/null; then
  echo "    key already present, skipping"
else
  echo "${SSH_PUBKEY}" >> "${AUTH_KEYS}"
fi
chown -R "${DEPLOY_USER}:${DEPLOY_USER}" "${SSH_DIR}"
chmod 700 "${SSH_DIR}"
chmod 600 "${AUTH_KEYS}"

echo ""
echo "Done."
