#!/usr/bin/env bash
# Usage: publish-photos.sh [vps-host] [branch]
# Can be called from any directory — no dependency on the repo being the working dir.
set -euo pipefail

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

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

# --- 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_PHOTOS'
"

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

# --- 2. Build + cleanup ---
ssh "$VPS" "
  set -euo pipefail
  cd '$REMOTE_BASE'
  podman-compose -f compose.yml up --build -d --force-recreate
  podman image prune -af
  podman builder prune -af
"

echo "Photos 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..."
  curl -s -X POST "https://webmention.app/check?url=https://adrian-altner.com/rss/photos.xml&token=${WEBMENTION_APP_TOKEN}" \
    | grep -o '"status":"[^"]*"' || true
  echo "Webmentions triggered."
else
  echo "No WEBMENTION_APP_TOKEN in .env.production — skipping webmentions."
fi
