#!/usr/bin/env bash
# Provision a host to render secrets from the SOPS vault at deploy time. Idempotent;
# run once per box (prod/beta) as a sudo-capable user.
#
#   SECRETS_ENV=prod AGE_KEY_SRC=/path/to/age.key bash deploy/provision-secrets.sh
#
# Installs `sops` + `age`, then installs the age PRIVATE key at /etc/thermograph/age.key
# (0400) and writes /etc/thermograph/secrets-env. After this, deploy.sh renders
# /etc/thermograph.env from deploy/secrets/*.yaml. See deploy/secrets/README.md.
set -euo pipefail

SECRETS_ENV="${SECRETS_ENV:?set SECRETS_ENV=prod|beta}"
AGE_KEY_SRC="${AGE_KEY_SRC:?set AGE_KEY_SRC=/path/to/the/age/private/key}"
SOPS_VERSION="${SOPS_VERSION:-v3.13.2}"
AGE_VERSION="${AGE_VERSION:-v1.3.1}"
BIN="${BIN:-/usr/local/bin}"
ARCH="$(uname -m)"; case "$ARCH" in x86_64) ARCH=amd64;; aarch64|arm64) ARCH=arm64;; esac

install_sops() {
  command -v sops >/dev/null 2>&1 && { echo "==> sops already installed"; return; }
  echo "==> Installing sops ${SOPS_VERSION}"
  sudo curl -fsSL "https://github.com/getsops/sops/releases/download/${SOPS_VERSION}/sops-${SOPS_VERSION}.linux.${ARCH}" -o "${BIN}/sops"
  sudo chmod +x "${BIN}/sops"
}

install_age() {
  command -v age >/dev/null 2>&1 && { echo "==> age already installed"; return; }
  echo "==> Installing age ${AGE_VERSION}"
  tmp="$(mktemp -d)"
  curl -fsSL "https://github.com/FiloSottile/age/releases/download/${AGE_VERSION}/age-${AGE_VERSION}-linux-${ARCH}.tar.gz" | tar -xz -C "$tmp"
  sudo install -m 0755 "$tmp/age/age" "$tmp/age/age-keygen" "$BIN/"
  rm -rf "$tmp"
}

install_sops
install_age

echo "==> Installing age key -> /etc/thermograph/age.key (0400) and marker (${SECRETS_ENV})"
sudo mkdir -p /etc/thermograph
sudo install -m 0400 "$AGE_KEY_SRC" /etc/thermograph/age.key
printf '%s\n' "$SECRETS_ENV" | sudo tee /etc/thermograph/secrets-env >/dev/null
sudo chmod 0644 /etc/thermograph/secrets-env

echo "==> Done. Verify:  sops --version && ls -l /etc/thermograph/"
echo "    Next: seed deploy/secrets/*.yaml, dry-run render, then deploy (see README)."
