#!/usr/bin/env bash
# publish-update-site.sh - build the thoughtframe-eclipse p2 update site and publish it to
# thoughtframe.ai.
#
# Why a plain file copy: the live site is a real directory inside the running webapp.
# thoughtframe.ai -> nginx -> container thoughtframe16 (172.25.0.16:8080), whose webapp is
# bind-mounted on the host at /media/netevolved/thoughtframe/webapp. The site is served from
# <webapp>/thoughtframe/eclipse/, so publishing is: build the site, sync that directory.
# No container restart, no WAR deploy, no p2 publisher on the server.
#
# Usage: eclipse/publish-update-site.sh [ssh-host]        (default: thoughtframe)
#   VERSION=1.2.3   fixed version (default: <manifest base>.<UTC yyyyMMddHHmm>, so every build
#                   is a distinct newer version and Eclipse offers it as an upgrade)
#   SITE=<dir>      reuse an already-built site instead of building again
set -euo pipefail

here="$(cd "$(dirname "$0")" && pwd)"
root="$(cd "$here/.." && pwd)"
host="${1:-thoughtframe}"
remote="/media/netevolved/thoughtframe/webapp/thoughtframe/eclipse"
site="${SITE:-$root/build/dist/site}"

if [ -z "${SITE:-}" ]; then
	echo "== 1/3 building the update site"
	bash "$here/make-update-site.sh" "$site"
else
	echo "== 1/3 reusing prebuilt site at $site"
fi

version="$(cat "$site/version.txt")"
echo "   version: $version"

echo "== 2/3 publishing -> $host:$remote"
ssh "$host" "mkdir -p '$remote'"
if command -v rsync >/dev/null 2>&1 && ssh "$host" 'command -v rsync >/dev/null 2>&1'; then
	rsync -a --delete "$site/" "$host:$remote/"
else
	echo "   rsync unavailable - using tar over ssh"
	ssh "$host" "rm -rf '$remote' && mkdir -p '$remote'"
	tar -C "$site" -cf - . | ssh "$host" "tar -C '$remote' -xf -"
fi

echo "== 3/3 verifying"
live="$(curl -s --max-time 25 https://thoughtframe.ai/thoughtframe/eclipse/version.txt || true)"
echo "   live version.txt: ${live:-<no answer>}"
if [ "$live" = "$version" ]; then
	echo "   OK: $version is live"
else
	echo "   WARN: live says '${live:-nothing}' - inspect the served dir" >&2
fi
