#!/bin/bash

###############################################################################
# AdHub Legacy SDK - Deploy su static.4wnetwork.com
#
# Questo script sostituisce il vecchio SDK 4wnetwork con il nuovo SDK Legacy
# SENZA modificare l'URL per i publisher.
#
# I publisher continuano a usare:
#   https://static.4wnetwork.com/js/sdk.min.js
#
# Usage:
#   ./deploy-4wnetwork.sh [--confirm]
#
###############################################################################

set -e  # Exit on error

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
NC='\033[0m' # No Color

# Configuration
PROJECT_ROOT="/var/www/html/adhub_prod"
SDK_SOURCE="$PROJECT_ROOT/sdk_legacy/dist/sdk.min.js"
BUNDLE_SOURCE="$PROJECT_ROOT/lib_adhubmedia/dist/legacy_adhubmedia"

# Target directories
TARGET_4W_SDK="/var/www/html/static.4wnetwork.com/js"
TARGET_ADHUB_BUNDLE="/var/www/html/lib.adhubmedia.com/dist/legacy_adhubmedia"

# Backup directory
BACKUP_DIR="$TARGET_4W_SDK/backups/$(date +%Y%m%d_%H%M%S)"

###############################################################################
# Functions
###############################################################################

print_header() {
  echo -e "${MAGENTA}"
  echo "╔═══════════════════════════════════════════════════════════════╗"
  echo "║                                                               ║"
  echo "║   AdHub Legacy SDK - Deploy 4wnetwork (Zero Changes)         ║"
  echo "║                                                               ║"
  echo "╚═══════════════════════════════════════════════════════════════╝"
  echo -e "${NC}"
}

print_section() {
  echo -e "\n${YELLOW}▶ $1${NC}\n"
}

print_success() {
  echo -e "${GREEN}✅ $1${NC}"
}

print_error() {
  echo -e "${RED}❌ $1${NC}"
}

print_warning() {
  echo -e "${YELLOW}⚠️  $1${NC}"
}

print_info() {
  echo -e "${BLUE}ℹ️  $1${NC}"
}

check_access() {
  print_section "Verifica Accesso Server"

  # Check 4wnetwork directory
  if [ ! -d "$TARGET_4W_SDK" ]; then
    print_error "Directory non trovata: $TARGET_4W_SDK"
    echo ""
    print_warning "Non hai accesso a static.4wnetwork.com?"
    echo ""
    echo "Opzioni:"
    echo "  1. Crea directory: mkdir -p $TARGET_4W_SDK"
    echo "  2. Verifica mount/permissions"
    echo "  3. Usa strategia alternativa (vedi MIGRATION_STRATEGY.md)"
    exit 1
  fi
  print_success "Accesso a static.4wnetwork.com: OK"

  # Check write permissions
  if [ ! -w "$TARGET_4W_SDK" ]; then
    print_error "Nessun permesso di scrittura su: $TARGET_4W_SDK"
    echo "Esegui: sudo chown -R $(whoami) $TARGET_4W_SDK"
    exit 1
  fi
  print_success "Permessi di scrittura: OK"

  # Check lib.adhubmedia.com directory
  if [ ! -d "$(dirname $TARGET_ADHUB_BUNDLE)" ]; then
    print_warning "Directory lib.adhubmedia.com non esiste"
    mkdir -p "$TARGET_ADHUB_BUNDLE"
    print_success "Directory creata: $TARGET_ADHUB_BUNDLE"
  fi
}

check_sources() {
  print_section "Verifica Files Sorgenti"

  # Check SDK source
  if [ ! -f "$SDK_SOURCE" ]; then
    print_error "SDK non trovato: $SDK_SOURCE"
    echo "Esegui prima: cd $PROJECT_ROOT/sdk_legacy && npm run build"
    exit 1
  fi

  local sdk_size=$(du -h "$SDK_SOURCE" | cut -f1)
  print_success "SDK Legacy trovato ($sdk_size)"

  # Check bundle source
  if [ ! -f "$BUNDLE_SOURCE/adhub-legacy_adhubmedia-no-cmp.min.js" ]; then
    print_error "Bundle AdHub non trovato: $BUNDLE_SOURCE"
    echo "Esegui il build in lib_adhubmedia"
    exit 1
  fi

  local bundle_size=$(du -h "$BUNDLE_SOURCE/adhub-legacy_adhubmedia-no-cmp.min.js" | cut -f1)
  print_success "Bundle AdHub trovato ($bundle_size)"
}

show_current_status() {
  print_section "Status Attuale"

  if [ -f "$TARGET_4W_SDK/sdk.min.js" ]; then
    local current_size=$(du -h "$TARGET_4W_SDK/sdk.min.js" | cut -f1)
    local current_date=$(stat -c %y "$TARGET_4W_SDK/sdk.min.js" | cut -d' ' -f1)
    print_info "SDK attuale su 4wnetwork:"
    echo "  File: $TARGET_4W_SDK/sdk.min.js"
    echo "  Size: $current_size"
    echo "  Date: $current_date"

    # Check if it's old or new SDK
    if grep -q "AdHub Legacy SDK" "$TARGET_4W_SDK/sdk.min.js" 2>/dev/null; then
      print_success "SDK già aggiornato (AdHub Legacy SDK)"
    else
      print_warning "SDK vecchio (4wnetwork originale)"
    fi
  else
    print_warning "Nessun SDK presente su 4wnetwork"
  fi
}

confirm_deployment() {
  print_section "Conferma Deployment"

  echo -e "${YELLOW}"
  echo "╔═══════════════════════════════════════════════════════════════╗"
  echo "║                    ⚠️  ATTENZIONE                             ║"
  echo "╚═══════════════════════════════════════════════════════════════╝"
  echo -e "${NC}"

  print_warning "Stai per sostituire il SDK su static.4wnetwork.com"
  print_warning "Questo avrà effetto immediato su TUTTI i publisher!"
  echo ""
  print_info "Verrà eseguito:"
  echo "  1. Backup vecchio SDK → $BACKUP_DIR"
  echo "  2. Deploy nuovo SDK Legacy → $TARGET_4W_SDK/sdk.min.js"
  echo "  3. Deploy bundle AdHub → $TARGET_ADHUB_BUNDLE"
  echo ""

  if [ "$1" != "--confirm" ]; then
    read -p "$(echo -e ${YELLOW}Continuare? ${NC}[yes/NO]: )" -r
    echo
    if [[ ! $REPLY =~ ^[Yy]es$ ]]; then
      print_error "Deploy annullato dall'utente"
      exit 1
    fi
  fi
}

backup_old_sdk() {
  print_section "Backup Vecchio SDK"

  if [ ! -f "$TARGET_4W_SDK/sdk.min.js" ]; then
    print_info "Nessun SDK esistente da fare backup"
    return
  fi

  # Create backup directory
  mkdir -p "$BACKUP_DIR"
  print_success "Directory backup creata: $BACKUP_DIR"

  # Backup SDK
  cp "$TARGET_4W_SDK/sdk.min.js" "$BACKUP_DIR/sdk.min.js.old"

  # Backup other files if exist
  [ -f "$TARGET_4W_SDK/sdk.js" ] && cp "$TARGET_4W_SDK/sdk.js" "$BACKUP_DIR/sdk.js.old"
  [ -f "$TARGET_4W_SDK/.htaccess" ] && cp "$TARGET_4W_SDK/.htaccess" "$BACKUP_DIR/.htaccess.old"

  local backup_size=$(du -sh "$BACKUP_DIR" | cut -f1)
  print_success "Backup completato ($backup_size)"
  print_info "Backup location: $BACKUP_DIR"
}

deploy_sdk() {
  print_section "Deploy Nuovo SDK Legacy"

  # Copy minified SDK
  cp "$SDK_SOURCE" "$TARGET_4W_SDK/sdk.min.js"
  print_success "Copiato: sdk.min.js"

  # Copy development version if exists
  if [ -f "$PROJECT_ROOT/sdk_legacy/dist/sdk.js" ]; then
    cp "$PROJECT_ROOT/sdk_legacy/dist/sdk.js" "$TARGET_4W_SDK/sdk.js"
    print_success "Copiato: sdk.js (development)"
  fi

  # Copy .htaccess
  if [ -f "$PROJECT_ROOT/sdk_legacy/dist/.htaccess" ]; then
    cp "$PROJECT_ROOT/sdk_legacy/dist/.htaccess" "$TARGET_4W_SDK/.htaccess"
    print_success "Copiato: .htaccess"
  fi

  # Set permissions
  chmod 644 "$TARGET_4W_SDK/sdk.min.js"
  [ -f "$TARGET_4W_SDK/sdk.js" ] && chmod 644 "$TARGET_4W_SDK/sdk.js"
  [ -f "$TARGET_4W_SDK/.htaccess" ] && chmod 644 "$TARGET_4W_SDK/.htaccess"
  print_success "Permessi impostati (644)"

  # Show new file info
  local new_size=$(du -h "$TARGET_4W_SDK/sdk.min.js" | cut -f1)
  print_success "Nuovo SDK deployed: $new_size"
}

deploy_bundle() {
  print_section "Deploy Bundle AdHub Legacy"

  # Create directory if not exists
  mkdir -p "$TARGET_ADHUB_BUNDLE"

  # Copy all bundle files
  cp "$BUNDLE_SOURCE"/*.js "$TARGET_ADHUB_BUNDLE/"
  print_success "Copiati: bundle JS files"

  # Copy documentation
  cp "$BUNDLE_SOURCE"/*.txt "$TARGET_ADHUB_BUNDLE/" 2>/dev/null || true
  print_success "Copiati: documentation files"

  # Set permissions
  chmod 644 "$TARGET_ADHUB_BUNDLE"/*.js
  chmod 644 "$TARGET_ADHUB_BUNDLE"/*.txt 2>/dev/null || true
  print_success "Permessi impostati"

  # Show bundle info
  local bundle_size=$(du -h "$TARGET_ADHUB_BUNDLE/adhub-legacy_adhubmedia-no-cmp.min.js" | cut -f1)
  print_success "Bundle deployed: $bundle_size"
}

verify_deployment() {
  print_section "Verifica Deployment"

  # Verify SDK
  if [ -f "$TARGET_4W_SDK/sdk.min.js" ]; then
    if grep -q "AdHub Legacy SDK" "$TARGET_4W_SDK/sdk.min.js"; then
      print_success "SDK Legacy verificato (contiene marker corretto)"
    else
      print_error "SDK non sembra essere quello giusto!"
      return 1
    fi
  else
    print_error "SDK non trovato dopo deploy!"
    return 1
  fi

  # Verify bundle
  if [ -f "$TARGET_ADHUB_BUNDLE/adhub-legacy_adhubmedia-no-cmp.min.js" ]; then
    print_success "Bundle AdHub verificato"
  else
    print_error "Bundle non trovato dopo deploy!"
    return 1
  fi

  print_success "Tutti i file verificati con successo"
}

test_urls() {
  print_section "Test URLs"

  print_info "Testare manualmente questi URL:"
  echo ""
  echo "  1. SDK 4wnetwork:"
  echo "     curl -I https://static.4wnetwork.com/js/sdk.min.js"
  echo ""
  echo "  2. Bundle AdHub:"
  echo "     curl -I https://lib.adhubmedia.com/dist/legacy_adhubmedia/adhub-legacy_adhubmedia-no-cmp.min.js"
  echo ""
  print_info "Dovresti vedere:"
  echo "  • HTTP/2 200"
  echo "  • content-type: application/javascript"
  echo "  • access-control-allow-origin: *"
}

create_rollback_script() {
  print_section "Creazione Script Rollback"

  local rollback_script="$BACKUP_DIR/rollback.sh"

  cat > "$rollback_script" << 'EOF'
#!/bin/bash
# Rollback script generated automatically
# Usage: ./rollback.sh

BACKUP_DIR="$(dirname "$0")"
TARGET_SDK="/var/www/html/static.4wnetwork.com/js"

echo "🔙 Rollback in corso..."

if [ -f "$BACKUP_DIR/sdk.min.js.old" ]; then
  cp "$BACKUP_DIR/sdk.min.js.old" "$TARGET_SDK/sdk.min.js"
  echo "✅ SDK ripristinato"
else
  echo "❌ Backup non trovato!"
  exit 1
fi

echo "✅ Rollback completato"
echo "Verifica: curl -I https://static.4wnetwork.com/js/sdk.min.js"
EOF

  chmod +x "$rollback_script"
  print_success "Script rollback creato: $rollback_script"
  print_info "Per rollback esegui: $rollback_script"
}

print_summary() {
  print_section "Summary Deployment"

  echo -e "${GREEN}"
  echo "╔═══════════════════════════════════════════════════════════════╗"
  echo "║                  ✅ DEPLOYMENT COMPLETATO                     ║"
  echo "╚═══════════════════════════════════════════════════════════════╝"
  echo -e "${NC}"

  print_success "SDK Legacy deployed su static.4wnetwork.com"
  print_success "Bundle AdHub deployed su lib.adhubmedia.com"
  print_success "Backup salvato in: $BACKUP_DIR"
  echo ""

  print_info "Publisher continuano a usare:"
  echo "  https://static.4wnetwork.com/js/sdk.min.js"
  echo ""
  print_info "SDK caricherà automaticamente:"
  echo "  https://lib.adhubmedia.com/dist/legacy_adhubmedia/"
  echo "    adhub-legacy_adhubmedia-no-cmp.min.js"
  echo ""

  print_warning "IMPORTANTE: Monitor console su siti publisher"
  echo "  Dovresti vedere: [AdHub Legacy SDK] ✅ SDK caricato v1.0.0"
  echo ""

  print_info "Next Steps:"
  echo "  1. Test su sito publisher live"
  echo "  2. Verifica console browser (F12)"
  echo "  3. Monitor revenue prime 24h"
  echo "  4. Clear CDN cache se presente"
  echo ""

  print_info "Rollback disponibile:"
  echo "  $BACKUP_DIR/rollback.sh"
}

###############################################################################
# Main Execution
###############################################################################

main() {
  print_header

  check_access
  check_sources
  show_current_status
  confirm_deployment "$1"
  backup_old_sdk
  deploy_sdk
  deploy_bundle
  verify_deployment
  test_urls
  create_rollback_script
  print_summary
}

# Run main
main "$@"

exit 0
