#!/bin/bash

###############################################################################
# Crea Package per Deploy SFTP
#
# Questo script crea un archivio pronto per l'upload via SFTP
# con tutti i file necessari e la struttura corretta
#
# Usage: ./create-deploy-package.sh
###############################################################################

set -e

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

PROJECT_ROOT="/var/www/html/adhub_prod/sdk_legacy"
BUNDLE_SOURCE="/var/www/html/adhub_prod/lib_adhubmedia/dist/legacy_adhubmedia"
PACKAGE_DIR="$PROJECT_ROOT/deploy_package"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
PACKAGE_NAME="adhub_legacy_sdk_${TIMESTAMP}"

echo -e "${BLUE}"
echo "╔═══════════════════════════════════════════════════════════════╗"
echo "║                                                               ║"
echo "║        Creazione Package Deploy SFTP                         ║"
echo "║                                                               ║"
echo "╚═══════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Pulisci e ricrea directory
echo -e "${YELLOW}📦 Preparazione directory...${NC}"
rm -rf "$PACKAGE_DIR"
mkdir -p "$PACKAGE_DIR/$PACKAGE_NAME"

# Crea struttura directory
mkdir -p "$PACKAGE_DIR/$PACKAGE_NAME/static.4wnetwork.com/js"
mkdir -p "$PACKAGE_DIR/$PACKAGE_NAME/lib.adhubmedia.com/dist/legacy_adhubmedia"

# Copia SDK Legacy
echo -e "${YELLOW}📄 Copia SDK Legacy...${NC}"
cp "$PROJECT_ROOT/dist/sdk.min.js" "$PACKAGE_DIR/$PACKAGE_NAME/static.4wnetwork.com/js/"
cp "$PROJECT_ROOT/dist/sdk.js" "$PACKAGE_DIR/$PACKAGE_NAME/static.4wnetwork.com/js/"
cp "$PROJECT_ROOT/dist/.htaccess" "$PACKAGE_DIR/$PACKAGE_NAME/static.4wnetwork.com/js/"
echo -e "${GREEN}✅ SDK copiato${NC}"

# Copia Bundle AdHub Legacy
echo -e "${YELLOW}📄 Copia Bundle AdHub...${NC}"
cp "$BUNDLE_SOURCE"/*.js "$PACKAGE_DIR/$PACKAGE_NAME/lib.adhubmedia.com/dist/legacy_adhubmedia/"
cp "$BUNDLE_SOURCE"/*.txt "$PACKAGE_DIR/$PACKAGE_NAME/lib.adhubmedia.com/dist/legacy_adhubmedia/" 2>/dev/null || true
echo -e "${GREEN}✅ Bundle copiato${NC}"

# Crea README per deploy
cat > "$PACKAGE_DIR/$PACKAGE_NAME/README_DEPLOY.txt" << 'EOF'
╔═══════════════════════════════════════════════════════════════╗
║                                                               ║
║     AdHub Legacy SDK - Package Deploy SFTP                   ║
║                                                               ║
╚═══════════════════════════════════════════════════════════════╝

📦 CONTENUTO PACKAGE:

static.4wnetwork.com/
└── js/
    ├── sdk.min.js      (24 KB) - SDK Legacy Production
    ├── sdk.js          (56 KB) - SDK Legacy Development
    └── .htaccess               - Configurazione CORS

lib.adhubmedia.com/
└── dist/
    └── legacy_adhubmedia/
        ├── adhub-legacy_adhubmedia-no-cmp.min.js  (135 KB)
        ├── adhub-legacy_adhubmedia.min.js         (141 KB)
        ├── adhub-legacy_adhubmedia-no-cmp.js      (359 KB)
        ├── adhub-legacy_adhubmedia.js             (377 KB)
        ├── ads.txt
        └── integration-guide*.txt

═══════════════════════════════════════════════════════════════

🚀 ISTRUZIONI UPLOAD SFTP:

1. BACKUP VECCHIO SDK (IMPORTANTE!)
   ────────────────────────────────
   Prima di caricare, scarica il vecchio sdk.min.js come backup:

   Percorso: /js/sdk.min.js
   Server: static.4wnetwork.com

   Salvalo come: sdk.min.js.backup_20251117


2. UPLOAD SU static.4wnetwork.com
   ──────────────────────────────────
   Server: static.4wnetwork.com

   Carica questi file:

   Local:  static.4wnetwork.com/js/sdk.min.js
   Remote: /js/sdk.min.js

   Local:  static.4wnetwork.com/js/sdk.js
   Remote: /js/sdk.js

   Local:  static.4wnetwork.com/js/.htaccess
   Remote: /js/.htaccess

   ⚠️  ATTENZIONE: Stai sostituendo il file esistente!
                  Assicurati di aver fatto il backup!


3. UPLOAD SU lib.adhubmedia.com
   ────────────────────────────────
   Server: lib.adhubmedia.com

   Carica intera directory:

   Local:  lib.adhubmedia.com/dist/legacy_adhubmedia/*
   Remote: /dist/legacy_adhubmedia/

   Tutti i file .js e .txt


4. VERIFICA PERMISSIONS
   ────────────────────────
   Dopo upload, verifica permissions:

   Files .js e .htaccess: 644 (rw-r--r--)

   Se necessario:
   chmod 644 /js/sdk.min.js
   chmod 644 /js/.htaccess
   chmod 644 /dist/legacy_adhubmedia/*.js


5. TEST DEPLOYMENT
   ──────────────────
   A) Test URL SDK:
      curl -I https://static.4wnetwork.com/js/sdk.min.js

      Aspettati:
      - HTTP/2 200
      - content-length: ~24000
      - access-control-allow-origin: *

   B) Test contenuto SDK:
      curl https://static.4wnetwork.com/js/sdk.min.js | head -n 3

      Aspettati:
      /**
       * AdHub Legacy SDK - Compatibility Layer for 4wnetwork tags
       * @version 1.0.0

   C) Test Bundle AdHub:
      curl -I https://lib.adhubmedia.com/dist/legacy_adhubmedia/adhub-legacy_adhubmedia-no-cmp.min.js

      Aspettati:
      - HTTP/2 200
      - content-length: ~135000

   D) Test Live su Sito Publisher:
      - Apri un sito publisher che usa i vecchi tag
      - F12 → Console
      - Cerca: "[AdHub Legacy SDK] ✅ SDK caricato v1.0.0"


6. ROLLBACK (se necessario)
   ─────────────────────────
   Se qualcosa va male:

   1. Carica il backup che hai fatto:
      sdk.min.js.backup_20251117 → /js/sdk.min.js

   2. Verifica che funzioni:
      curl -I https://static.4wnetwork.com/js/sdk.min.js

═══════════════════════════════════════════════════════════════

📊 COSA CAMBIA PER I PUBLISHER:

✅ NIENTE!

I publisher mantengono esattamente lo stesso codice:
<script src="https://static.4wnetwork.com/js/sdk.min.js"></script>

Il nuovo SDK:
• Parse i vecchi tag obj_4w
• Genera placeholder AdHub
• Carica automaticamente il bundle da lib.adhubmedia.com
• Renderizza gli ads

═══════════════════════════════════════════════════════════════

📞 SUPPORT:

In caso di problemi:
- Esegui rollback (punto 6)
- Contatta: tech-support@adhubmedia.com

═══════════════════════════════════════════════════════════════

Build: 2025-11-17
Version: 1.0.0

EOF

echo -e "${GREEN}✅ README creato${NC}"

# Crea checklist deploy
cat > "$PACKAGE_DIR/$PACKAGE_NAME/CHECKLIST_DEPLOY.txt" << 'EOF'
╔═══════════════════════════════════════════════════════════════╗
║           CHECKLIST DEPLOYMENT                                ║
╚═══════════════════════════════════════════════════════════════╝

PRE-DEPLOYMENT:
[ ] Build completato localmente
[ ] Files verificati in questo package
[ ] Accesso SFTP testato
[ ] Backup plan pronto

BACKUP (IMPORTANTE!):
[ ] Scaricato backup di: /js/sdk.min.js (da static.4wnetwork.com)
[ ] Salvato come: sdk.min.js.backup_YYYYMMDD
[ ] Backup verificato e funzionante

UPLOAD static.4wnetwork.com:
[ ] Caricato: /js/sdk.min.js (24 KB)
[ ] Caricato: /js/sdk.js (56 KB) - opzionale
[ ] Caricato: /js/.htaccess
[ ] Permissions verificate: 644

UPLOAD lib.adhubmedia.com:
[ ] Caricato: /dist/legacy_adhubmedia/*.min.js (tutti i file)
[ ] Caricato: /dist/legacy_adhubmedia/*.txt (docs)
[ ] Permissions verificate: 644

VERIFICA:
[ ] Test curl SDK: https://static.4wnetwork.com/js/sdk.min.js
[ ] Test curl Bundle: https://lib.adhubmedia.com/dist/legacy_adhubmedia/*.min.js
[ ] Test browser console su sito publisher
[ ] Log "[AdHub Legacy SDK]" visibili
[ ] Placeholder generati nel DOM
[ ] Annunci visualizzati correttamente
[ ] Nessun errore JavaScript

MONITORING (prime 24h):
[ ] Revenue stabile/migliorata
[ ] Nessun errore segnalato
[ ] Performance OK
[ ] Clear CDN cache (se presente)

ROLLBACK DISPONIBILE:
[ ] File backup salvato e accessibile
[ ] Procedura rollback testata
[ ] Team notificato

FIRMA:
Data: _______________
Nome: _______________
Note: _______________

EOF

echo -e "${GREEN}✅ Checklist creata${NC}"

# Crea file con info build
cat > "$PACKAGE_DIR/$PACKAGE_NAME/BUILD_INFO.txt" << EOF
╔═══════════════════════════════════════════════════════════════╗
║           BUILD INFORMATION                                   ║
╚═══════════════════════════════════════════════════════════════╝

Build Date: $(date '+%Y-%m-%d %H:%M:%S')
Build Host: $(hostname)
Build User: $(whoami)

SDK Version: 1.0.0
Package: adhub_legacy_sdk_${TIMESTAMP}

FILES INCLUDED:
──────────────

SDK Legacy (static.4wnetwork.com):
  sdk.min.js        $(du -h "$PROJECT_ROOT/dist/sdk.min.js" | cut -f1)
  sdk.js            $(du -h "$PROJECT_ROOT/dist/sdk.js" | cut -f1)
  .htaccess         $(du -h "$PROJECT_ROOT/dist/.htaccess" | cut -f1)

Bundle AdHub (lib.adhubmedia.com):
  adhub-legacy_adhubmedia-no-cmp.min.js    $(du -h "$BUNDLE_SOURCE/adhub-legacy_adhubmedia-no-cmp.min.js" | cut -f1)
  adhub-legacy_adhubmedia.min.js           $(du -h "$BUNDLE_SOURCE/adhub-legacy_adhubmedia.min.js" | cut -f1)
  (+ development versions + docs)

TOTAL PACKAGE SIZE: $(du -sh "$PACKAGE_DIR/$PACKAGE_NAME" | cut -f1)

CHECKSUMS (MD5):
────────────────
SDK:    $(md5sum "$PROJECT_ROOT/dist/sdk.min.js" | cut -d' ' -f1)
Bundle: $(md5sum "$BUNDLE_SOURCE/adhub-legacy_adhubmedia-no-cmp.min.js" | cut -d' ' -f1)

EOF

echo -e "${GREEN}✅ Build info creato${NC}"

# Crea archivio ZIP
echo -e "${YELLOW}📦 Creazione archivio ZIP...${NC}"
cd "$PACKAGE_DIR"
zip -r "${PACKAGE_NAME}.zip" "$PACKAGE_NAME" > /dev/null
echo -e "${GREEN}✅ Archivio creato${NC}"

# Crea anche tar.gz
echo -e "${YELLOW}📦 Creazione archivio TAR.GZ...${NC}"
tar -czf "${PACKAGE_NAME}.tar.gz" "$PACKAGE_NAME"
echo -e "${GREEN}✅ Archivio creato${NC}"

# Summary
echo ""
echo -e "${GREEN}"
echo "╔═══════════════════════════════════════════════════════════════╗"
echo "║               ✅ PACKAGE CREATO CON SUCCESSO                  ║"
echo "╚═══════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

echo -e "${BLUE}📁 Package location:${NC}"
echo "  Directory: $PACKAGE_DIR/$PACKAGE_NAME/"
echo "  ZIP:       $PACKAGE_DIR/${PACKAGE_NAME}.zip"
echo "  TAR.GZ:    $PACKAGE_DIR/${PACKAGE_NAME}.tar.gz"
echo ""

echo -e "${BLUE}📊 Package info:${NC}"
echo "  Directory size: $(du -sh "$PACKAGE_DIR/$PACKAGE_NAME" | cut -f1)"
echo "  ZIP size:       $(du -h "$PACKAGE_DIR/${PACKAGE_NAME}.zip" | cut -f1)"
echo "  TAR.GZ size:    $(du -h "$PACKAGE_DIR/${PACKAGE_NAME}.tar.gz" | cut -f1)"
echo ""

echo -e "${BLUE}📝 Files inclusi:${NC}"
echo "  ├── static.4wnetwork.com/js/"
echo "  │   ├── sdk.min.js (24 KB)"
echo "  │   ├── sdk.js (56 KB)"
echo "  │   └── .htaccess"
echo "  ├── lib.adhubmedia.com/dist/legacy_adhubmedia/"
echo "  │   ├── *.min.js (bundles)"
echo "  │   ├── *.js (dev versions)"
echo "  │   └── *.txt (docs)"
echo "  ├── README_DEPLOY.txt"
echo "  ├── CHECKLIST_DEPLOY.txt"
echo "  └── BUILD_INFO.txt"
echo ""

echo -e "${YELLOW}📤 Next Steps:${NC}"
echo "  1. Scarica il package:"
echo "     scp user@server:$PACKAGE_DIR/${PACKAGE_NAME}.zip ."
echo ""
echo "  2. Estrai localmente:"
echo "     unzip ${PACKAGE_NAME}.zip"
echo ""
echo "  3. Leggi README_DEPLOY.txt per istruzioni upload SFTP"
echo ""
echo "  4. Usa CHECKLIST_DEPLOY.txt durante il deploy"
echo ""

echo -e "${GREEN}✅ Pronto per upload SFTP!${NC}"

exit 0
