#!/usr/bin/env bash
# Copies bootstrap-deploy-user.sh to the server and runs it as root.
# Run from the repo root: bash scripts/run-bootstrap.sh
#
# Requires: ssh access to the server as root via keys/root_cloud_ladkau_de

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

SERVER=$(grep -oP '(?<=ansible_host=)\S+' "${REPO_ROOT}/ansible/inventory.ini" | head -1)
if [ -z "${SERVER}" ]; then
  echo "ERROR: could not find ansible_host in ansible/inventory.ini" >&2
  exit 1
fi

ROOT_KEY="${REPO_ROOT}/keys/root_cloud_ladkau_de"
DEPLOY_KEY="${REPO_ROOT}/keys/notroot_cloud_ladkau_de"
DEPLOY_PUBKEY="${REPO_ROOT}/keys/notroot_cloud_ladkau_de.pub"
BOOTSTRAP_SCRIPT="${SCRIPT_DIR}/bootstrap-deploy-user.sh"

# --- Preflight checks ---

if [ ! -f "${ROOT_KEY}" ]; then
  echo "ERROR: root SSH key not found at ${ROOT_KEY}" >&2
  exit 1
fi

if [ ! -f "${DEPLOY_KEY}" ]; then
  echo "ERROR: deploy SSH key not found at ${DEPLOY_KEY}" >&2
  exit 1
fi

if [ ! -f "${DEPLOY_PUBKEY}" ]; then
  echo "ERROR: deploy public key not found at ${DEPLOY_PUBKEY}" >&2
  exit 1
fi

if [ ! -f "${BOOTSTRAP_SCRIPT}" ]; then
  echo "ERROR: bootstrap script not found at ${BOOTSTRAP_SCRIPT}" >&2
  exit 1
fi

# SSH private keys must not be group/world readable
chmod 600 "${ROOT_KEY}" "${DEPLOY_KEY}"

# --- Vault check ---

bash "${SCRIPT_DIR}/check-vault.sh"

SSH_OPTS="-o StrictHostKeyChecking=accept-new -o ConnectTimeout=10"

# --- Verify root access ---

echo "==> Verifying root SSH access to ${SERVER}"
if ! ssh ${SSH_OPTS} -i "${ROOT_KEY}" "root@${SERVER}" "echo ok" 2>/tmp/ssh_root_err; then
  echo "ERROR: cannot connect as root to ${SERVER}" >&2
  echo "       SSH error: $(cat /tmp/ssh_root_err)" >&2
  echo "" >&2
  echo "Possible causes:" >&2
  echo "  - Root public key not uploaded to the server (Strato control panel)" >&2
  echo "  - Wrong key file: ${ROOT_KEY}" >&2
  echo "  - Server not yet reachable (still booting?)" >&2
  rm -f /tmp/ssh_root_err
  exit 1
fi
rm -f /tmp/ssh_root_err

# --- Copy and run the bootstrap script ---

echo "==> Copying bootstrap script to server"
scp ${SSH_OPTS} -i "${ROOT_KEY}" "${BOOTSTRAP_SCRIPT}" "root@${SERVER}:/root/bootstrap-deploy-user.sh"

echo "==> Running bootstrap script on server"
SSH_PUBKEY="$(cat "${DEPLOY_PUBKEY}")"
ssh ${SSH_OPTS} -i "${ROOT_KEY}" "root@${SERVER}" "bash /root/bootstrap-deploy-user.sh '${SSH_PUBKEY}'"

# --- Verify deploy user access ---

echo ""
echo "==> Verifying deploy user SSH access"
if ssh ${SSH_OPTS} -i "${DEPLOY_KEY}" "deploy@${SERVER}" "echo ok" &>/dev/null; then
  echo "    OK — deploy user can log in"
else
  echo "ERROR: deploy user login failed — check the bootstrap output above" >&2
  exit 1
fi

echo ""
echo "Bootstrap complete. Next step:"
echo "  ansible-playbook -i ansible/inventory.ini ansible/site.yml --ask-vault-pass"
