#!/bin/bash
# Install/update secrets-issuance on LXC 105 (apps). Idempotent.
set -euo pipefail

REPO_DIR=${REPO_DIR:-/opt/secrets-issuance}

cd "$REPO_DIR"
echo "[deploy] git pull"
git pull --ff-only

echo "[deploy] ensure python venv + deps"
if [ ! -d /opt/secrets-issuance/.venv ]; then
    python3 -m venv /opt/secrets-issuance/.venv
fi
/opt/secrets-issuance/.venv/bin/pip install --quiet --upgrade pip
/opt/secrets-issuance/.venv/bin/pip install --quiet pyyaml

echo "[deploy] verify dependencies (age, shred)"
command -v age-keygen >/dev/null || { echo "age-keygen not installed: apt install -y age" >&2; exit 1; }
command -v shred >/dev/null     || { echo "shred not installed: apt install -y coreutils" >&2; exit 1; }

echo "[deploy] state dir"
install -d -m 700 /var/lib/secrets-issuance
install -d -m 700 /var/lib/secrets-issuance/keys

echo "[deploy] admin token dir"
install -d -m 700 /etc/secrets-issuance
if [ ! -s /etc/secrets-issuance/admin-token ]; then
    head -c 32 /dev/urandom | base64 > /etc/secrets-issuance/admin-token
    chmod 600 /etc/secrets-issuance/admin-token
    echo "[deploy] generated admin token at /etc/secrets-issuance/admin-token"
fi

echo "[deploy] install systemd units"
install -m 644 secrets-issuance/server.service \
               /etc/systemd/system/secrets-issuance.service
install -m 644 secrets-issuance/deploy/webhook/secrets-issuance-deploy.service \
               /etc/systemd/system/secrets-issuance-deploy.service
install -m 755 secrets-issuance/backup.sh /usr/local/bin/secrets-issuance-backup
install -m 644 secrets-issuance/backup.service \
               /etc/systemd/system/secrets-issuance-backup.service
install -m 644 secrets-issuance/backup.timer \
               /etc/systemd/system/secrets-issuance-backup.timer

if [ ! -d /opt/homelab-context/.git ]; then
    echo "  /opt/homelab-context is not a git clone — run bootstrap.sh first." >&2
    exit 1
fi

systemctl daemon-reload
if systemctl is-active --quiet secrets-issuance.service; then
    systemctl restart secrets-issuance.service
fi
if systemctl is-active --quiet secrets-issuance-deploy.service; then
    systemctl restart secrets-issuance-deploy.service
fi

echo "[deploy] daemon-reload + enable backup timer"
systemctl daemon-reload
systemctl enable --now secrets-issuance-backup.timer

echo "[deploy] done"
echo "First-time enable:"
echo "  systemctl enable --now secrets-issuance.service secrets-issuance-deploy.service"
echo "Webhook first-time setup:"
echo "  $REPO_DIR/secrets-issuance/deploy/webhook/install.sh"
