#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO="$(dirname "$SCRIPT_DIR")"
DIST="$REPO/dist"
REMOTE="server1"
REMOTE_PATH="/home/hostingd/public_html"

echo "=== Deploy hostingdelsur.net (rsync) ==="
echo "Repo: $REPO"
echo "Dist: $DIST"
echo "Remote: $REMOTE:$REMOTE_PATH"
echo ""

# Build if dist doesn't exist or is stale
if [ ! -d "$DIST" ] || [ "$REPO/package.json" -nt "$DIST" ]; then
	echo "→ Building..."
	npm run build --prefix "$REPO"
fi

# Copy PHP endpoints into dist (they don't go through Astro)
mkdir -p "$DIST/api"
cp "$REPO/src/forms/contact.php" "$DIST/api/contact.php"
cp "$REPO/src/forms/deploy-webhook.php" "$DIST/api/deploy-webhook.php"
cp "$REPO/src/forms/api-htaccess" "$DIST/api/.htaccess"

# Copy root .htaccess (HTTPS forzado, security headers)
cp "$REPO/scripts/htaccess.conf" "$DIST/.htaccess"

# cPanel recognizes 404.shtml specifically (Server-Side Includes)
# Astro generates 404.html — duplicate as .shtml for cPanel
if [ -f "$DIST/404.html" ]; then
	cp "$DIST/404.html" "$DIST/404.shtml"
fi

# Extract shared design-system partials for WordPress /blog/
bash "$REPO/scripts/build-design-system.sh"

# rsync with --delete to mirror
# Preserve: mwp/, mee/ (SES Bounce Monitor), .well-known/, blog/ (WP), design-system/ (shared), smtp creds
rsync -avz --delete \
	--exclude='mwp' \
	--exclude='mee' \
	--exclude='.well-known' \
	--exclude='.smtp-credentials.json' \
	--exclude='blog' \
	-e ssh \
	"$DIST/" \
	"$REMOTE:$REMOTE_PATH/"

echo ""
echo "=== Verificación ==="
ssh $REMOTE "ls -la /home/hostingd/public_html/api/ && echo '---' && ls /home/hostingd/public_html/mwp/ | head -3 && echo '---' && ls /home/hostingd/public_html/design-system/ | head -10"
