#!/bin/bash
set -e

DIST="/root/opencode/development/hostingdelsur.net/dist"
REMOTE="server1"
REMOTE_PATH="/home/hostingd/public_html"
LOCAL_USER="root"

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

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

# Copy root .htaccess (HTTPS forzado, security headers)
cp /root/opencode/development/hostingdelsur.net/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

# rsync with --delete to mirror (preserva mwp/, .well-known/, etc.)
rsync -avz --delete \
  --exclude='mwp' \
  --exclude='.well-known' \
  --exclude='.smtp-credentials.json' \
  -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"
