#!/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 ==="
echo "Local dist: $DIST"
echo "Remote: $REMOTE:$REMOTE_PATH"
echo "Preserving: mwp/, .well-known/, .smtp-credentials.json (initially)"
echo ""

# lftp sync: borra archivos del remote que no estén en local,
# sube los nuevos, NO toca mwp/ ni .well-known/
lftp -c "
set sftp:auto-confirm yes
set ssl:verify-certificate no
open -u $LOCAL_USER sftp://$REMOTE
cd $REMOTE_PATH

# 1. Backup de archivos críticos a tmp antes de limpiar
mkdir -p /tmp/hds-deploy-backup
mv .smtp-credentials.json /tmp/hds-deploy-backup/ 2>/dev/null || true

# 2. Limpiar lo que va a ser reemplazado
# (NO borra mwp/ ni .well-known/)
glob rm -rf '!(mwp|.well-known)'
echo '=== Archivos restantes tras limpieza ==='
ls -la

# 3. Subir dist
mirror --reverse --delete --verbose=1 $DIST/ ./

# 4. Restaurar credenciales (se moverán después a /home/hostingd/)
mv /tmp/hds-deploy-backup/.smtp-credentials.json ./ 2>/dev/null || true

echo ''
echo '=== Resultado ==='
ls -la
"
echo ""
echo "=== Verificación mwp intacto ==="
ssh $REMOTE "ls /home/hostingd/public_html/mwp/ | head -5" 2>&1
echo ""
echo "=== Files deployed ==="
ssh $REMOTE "find /home/hostingd/public_html -maxdepth 1 -type d" 2>&1
