#!/usr/bin/env bash
# ═══════════════════════════════════════════════════════════════════════════
#  deploy-ftp.sh – Push mona.web.saas → ftp.mona.expert (enterprise)
#  ═══════════════════════════════════════════════════════════════════════════
#  Uploads this directory (excluding config, node_modules, .git, .env, certs)
#  to the production webserver via FTP using parallel curl uploads.
#
#  Usage:  ./deploy-ftp.sh
# ═══════════════════════════════════════════════════════════════════════════

set -euo pipefail

SERVER="ftp.mona.expert"
USER="u702975565.71818838838kwkksskd"
PASS="2342423423safaSD:"
REMOTE_DIR="/home/u702975565/domains/mona.expert/public_html"

EXCLUDE_PATTERNS=(
  "-not" "-name" "node_modules"
  "-not" "-path" "*/node_modules/*"
  "-not" "-name" ".git"
  "-not" "-path" "*/.git/*"
  "-not" "-name" ".env"
  "-not" "-name" ".env.*"
  "-not" "-name" "*.pem"
  "-not" "-name" "*.key"
  "-not" "-name" "*.crt"
  "-not" "-name" "*.csr"
  "-not" "-path" "*/certs/*"
  "-not" "-name" "deploy-ftp.sh"
  "-not" "-name" "deploy.log"
)

SOURCE_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SOURCE_DIR"

echo "═══════════════════════════════════════════════════════════════"
echo "  mona.web.saas → FTP Enterprise Deploy"
echo "  Source: $SOURCE_DIR"
echo "  Target: $SERVER"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Collect file list
FILES=()
while IFS= read -r -d '' f; do
  FILES+=("$f")
done < <(find . -type f "${EXCLUDE_PATTERNS[@]}" -print0 2>/dev/null)

TOTAL=${#FILES[@]}
echo "📦 $TOTAL files to deploy"
echo ""

# Create remote dirs via a single find + mkdir pass
echo "📁 Creating remote directories..."
dirs=$(find . -type d "${EXCLUDE_PATTERNS[@]}" 2>/dev/null | sed 's/^\.//')
for d in $dirs; do
  curl -s --user "$USER:$PASS" --ftp-create-dirs "ftp://$SERVER$REMOTE_DIR$d/" >/dev/null 2>&1 &
done
wait
echo "✅ Directories ready"
echo ""

# Upload with parallel background jobs (max 8 concurrent)
echo "⬆️  Uploading (8 parallel)…"
MAX_JOBS=8
COUNT=0
SUCCESS=0
FAILED=0

upload_one() {
  local file="$1"
  local rel="${file#./}"
  local remote_path="$REMOTE_DIR/$rel"
  if curl -s --user "$USER:$PASS" -T "$file" "ftp://$SERVER$remote_path" >/dev/null 2>&1; then
    echo "  ✅ $rel"
    return 0
  else
    echo "  ❌ $rel"
    return 1
  fi
}

for file in "${FILES[@]}"; do
  upload_one "$file" &
  COUNT=$((COUNT + 1))

  # Throttle: wait if we have MAX_JOBS running
  if [ $((COUNT % MAX_JOBS)) -eq 0 ]; then
    wait
  fi
done
wait

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "  ✅ Deploy complete"
echo "  📍 https://mona.expert/dashboard.html"
echo "═══════════════════════════════════════════════════════════════"
