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

VAULT_CONTENT='/Users/adrian/Obsidian/Web/adrian-altner-com/content'
VPS="${1:-hetzner}"
REMOTE_BRANCH="${2:-main}"

REMOTE_BASE='/opt/websites/adrian-altner.com'
REMOTE_CONTENT="${REMOTE_BASE}/src/content"

# --- 1. Sync vault to VPS ---
ssh "$VPS" "
  set -euo pipefail
  cd '$REMOTE_BASE'
  git fetch --prune origin '$REMOTE_BRANCH'
  git checkout '$REMOTE_BRANCH'
  git reset --hard 'origin/$REMOTE_BRANCH'
  git clean -fd -e .env -e .env.production
  mkdir -p '$REMOTE_CONTENT'
"

rsync -az --delete \
  --include='*/' \
  --include='*.md' \
  --include='*.mdx' \
  --include='*.jpg' \
  --include='*.jpeg' \
  --include='*.JPG' \
  --include='*.JPEG' \
  --include='*.json' \
  --exclude='.DS_Store' \
  --exclude='*' \
  "$VAULT_CONTENT/" "$VPS:$REMOTE_CONTENT/"

# --- 2. Build + cleanup ---
ssh "$VPS" "
  set -euo pipefail
  cd '$REMOTE_BASE'
  sudo podman build -t localhost/adrian-altner.com:latest .
  sudo systemctl restart podman-compose@adrian-altner.com.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 "Redeploy 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/blog.xml rss/notes.xml rss/links.xml rss/photos.xml; do
    curl -s -X POST "https://webmention.app/check?url=https://adrian-altner.com/${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