#!/usr/bin/env bash
set -euo pipefail

VPS="${1:-hetzner}"
REMOTE_BRANCH="${2:-main}"
REMOTE_BASE='/opt/websites/adrian-altner.de'
REMOTE_URL='ssh://git@git.altner.cloud:2222/adrian/adrian-altner.de.git'
GIT_HOST='git.altner.cloud'
GIT_PORT='2222'

# --- 1. Pull latest from repo ---
ssh "$VPS" "
  set -euo pipefail
  cd '$REMOTE_BASE'
  mkdir -p ~/.ssh && touch ~/.ssh/known_hosts && chmod 600 ~/.ssh/known_hosts
  ssh-keygen -F '[$GIT_HOST]:$GIT_PORT' >/dev/null || ssh-keyscan -p '$GIT_PORT' '$GIT_HOST' >> ~/.ssh/known_hosts
  git remote set-url origin '$REMOTE_URL'
  git fetch --prune origin '$REMOTE_BRANCH'
  git checkout '$REMOTE_BRANCH'
  git reset --hard 'origin/$REMOTE_BRANCH'
  git clean -fd -e .env -e .env.production
"

# --- 2. Build + deploy ---
ssh "$VPS" "
  set -euo pipefail
  cd '$REMOTE_BASE'
  sudo podman build -t localhost/adrian-altner.de:latest .
  sudo systemctl restart podman-compose@adrian-altner.de.service
  sudo podman container prune -f 2>/dev/null || true
  sudo podman image prune --external -f 2>/dev/null || true
  sudo podman image prune -f 2>/dev/null || true
  sudo podman builder prune -af 2>/dev/null || true
"

echo "Deploy done via $VPS (branch: $REMOTE_BRANCH)."

# --- 3. Webmentions ---
WEBMENTION_APP_TOKEN="$(ssh "$VPS" "grep '^WEBMENTION_APP_TOKEN=' '$REMOTE_BASE/.env.production' | cut -d= -f2-" 2>/dev/null || true)"
if [[ -n "$WEBMENTION_APP_TOKEN" ]]; then
  echo "Sending webmentions via webmention.app..."
  for feed in rss.xml en/rss.xml; do
    curl -s -X POST "https://webmention.app/check?url=https://adrian-altner.de/${feed}&token=${WEBMENTION_APP_TOKEN}" \
      | grep -o '"status":"[^"]*"' || true
  done
  echo "Webmentions triggered."
else
  echo "No WEBMENTION_APP_TOKEN in .env.production — skipping webmentions."
fi
