#!/usr/bin/env bash
# Bootstrap or refresh playground on boka from Gitea.
# Run from dev machine: ./scripts/bootstrap-boka.sh
set -euo pipefail

REMOTE_HOST="${REMOTE_HOST:-frank-schwenk.de}"
REMOTE_PATH="${REMOTE_PATH:-/home/frank/playground.schwenk.online}"
GITEA_REPO="ssh://git@gitea.schwenk.online:2222/froxxxy/playground.git"

ssh "${REMOTE_HOST}" bash -s <<EOF
set -euo pipefail
GITEA_REPO="${GITEA_REPO}"
REMOTE_PATH="${REMOTE_PATH}"

ENV_BACKUP=""
if [ -f "\${REMOTE_PATH}/.env" ]; then
  ENV_BACKUP=\$(mktemp)
  cp "\${REMOTE_PATH}/.env" "\${ENV_BACKUP}"
fi

if [ -d "\${REMOTE_PATH}" ]; then
  cd "\${REMOTE_PATH}"
  docker compose down 2>/dev/null || true
  cd /home/frank
  mv "\${REMOTE_PATH}" "\${REMOTE_PATH}.bak.\$(date +%s)"
fi

git clone "\${GITEA_REPO}" "\${REMOTE_PATH}"
cd "\${REMOTE_PATH}"

if [ -n "\${ENV_BACKUP}" ] && [ -f "\${ENV_BACKUP}" ]; then
  cp "\${ENV_BACKUP}" .env
  rm -f "\${ENV_BACKUP}"
elif [ ! -f .env ]; then
  WEBHOOK_SECRET=\$(openssl rand -hex 32)
  cat > .env <<ENVEOF
WEBHOOK_SECRET=\${WEBHOOK_SECRET}
DEPLOY_GIT_TOKEN=
HOST_UID=\$(id -u)
HOST_GID=\$(id -g)
ENVEOF
  echo "Created .env with generated WEBHOOK_SECRET:"
  grep WEBHOOK_SECRET .env
fi

grep -q '^HOST_UID=' .env 2>/dev/null || echo "HOST_UID=\$(id -u)" >> .env
grep -q '^HOST_GID=' .env 2>/dev/null || echo "HOST_GID=\$(id -g)" >> .env

docker compose up -d --build
docker compose ps
EOF

echo "Bootstrap finished: ${REMOTE_PATH} is a git clone of ${GITEA_REPO}"
