#!/bin/bash\n\n# ============================================\n# TagneticAI Email Client - Server Deployment\n# ============================================\n# Deploy to WHMCS/cPanel server\n# Run: bash deploy.sh\n\nset -e\n\necho \"🚀 TagneticAI Email Client Deployment\"\necho \"======================================\"\n\n# Color codes\nGREEN='\\033[0;32m'\nBLUE='\\033[0;34m'\nYELLOW='\\033[1;33m'\nNC='\\033[0m' # No Color\n\n# Check if running as root\nif [[ $EUID -ne 0 ]]; then\n   echo -e \"${YELLOW}⚠️  This script should be run as root${NC}\"\n   echo \"Try: sudo bash deploy.sh\"\n   exit 1\nfi\n\n# ============================================\n# Step 1: Install Dependencies\n# ============================================\necho -e \"\\n${BLUE}📦 Installing dependencies...${NC}\"\n\n# Update package manager\napt-get update -qq\n\n# Install Node.js if not present\nif ! command -v node &> /dev/null; then\n    echo \"Installing Node.js 20...\"\n    curl -fsSL https://deb.nodesource.com/setup_20.x | bash -\n    apt-get install -y nodejs\nelse\n    echo -e \"${GREEN}✓${NC} Node.js already installed: $(node --version)\"\nfi\n\n# Install pm2 globally for process management\nif ! command -v pm2 &> /dev/null; then\n    echo \"Installing PM2 for process management...\"\n    npm install -g pm2\n    pm2 startup\nelse\n    echo -e \"${GREEN}✓${NC} PM2 already installed\"\nfi\n\n# Install Nginx if not present\nif ! command -v nginx &> /dev/null; then\n    echo \"Installing Nginx...\"\n    apt-get install -y nginx\n    systemctl start nginx\n    systemctl enable nginx\nelse\n    echo -e \"${GREEN}✓${NC} Nginx already installed\"\nfi\n\n# ============================================\n# Step 2: Create Application Directory\n# ============================================\necho -e \"\\n${BLUE}📁 Setting up application directory...${NC}\"\n\nAPP_DIR=\"/opt/tagneticai-email\"\n\nif [ ! -d \"$APP_DIR\" ]; then\n    mkdir -p $APP_DIR\n    echo \"Created $APP_DIR\"\nelse\n    echo \"Directory already exists\"\nfi\n\ncd $APP_DIR\n\n# ============================================\n# Step 3: Copy Application Files\n# ============================================\necho -e \"\\n${BLUE}📋 Preparing application files...${NC}\"\necho \"Please upload the project files to: $APP_DIR\"\necho \"Then run: bash deploy.sh --deploy\"\n\n# Check if files exist\nif [ ! -f \"package.json\" ]; then\n    echo -e \"${YELLOW}⚠️  package.json not found!${NC}\"\n    echo \"Please:\"\n    echo \"  1. Upload all project files to $APP_DIR\"\n    echo \"  2. Run: bash deploy.sh --deploy\"\n    exit 0\nfi\n\n# ============================================\n# Step 4: Install Dependencies\n# ============================================\necho -e \"\\n${BLUE}🔧 Installing Node packages...${NC}\"\n\nif [ -f \"package-lock.json\" ]; then\n    npm ci\nelse\n    npm install\nfi\n\n# ============================================\n# Step 5: Build Application\n# ============================================\necho -e \"\\n${BLUE}🏗️  Building Next.js application...${NC}\"\n\nnpm run build\n\n# ============================================\n# Step 6: Environment Setup\n# ============================================\necho -e \"\\n${BLUE}⚙️  Configuring environment...${NC}\"\n\nif [ ! -f \".env\" ]; then\n    echo \"Creating .env file...\"\n    cp .env.example .env\n    echo -e \"${YELLOW}⚠️  IMPORTANT: Edit .env with your mail server credentials:${NC}\"\n    echo \"  nano /opt/tagneticai-email/.env\"\nelse\n    echo -e \"${GREEN}✓${NC} .env file exists\"\nfi\n\n# ============================================\n# Step 7: PM2 Setup\n# ============================================\necho -e \"\\n${BLUE}🚀 Starting application with PM2...${NC}\"\n\n# Stop if already running\npm2 delete tagneticai-email 2>/dev/null || true\n\n# Start with PM2\npm2 start npm --name \"tagneticai-email\" -- start\npm2 save\npm2 startup\n\necho -e \"${GREEN}✓${NC} Application started with PM2\"\n\n# ============================================\n# Step 8: Nginx Configuration\n# ============================================\necho -e \"\\n${BLUE}🌐 Configuring Nginx...${NC}\"\n\nread -p \"Enter domain name (email.tagneticai.com): \" DOMAIN\nDOMAIN=${DOMAIN:-email.tagneticai.com}\n\ncat > /etc/nginx/sites-available/tagneticai-email << EOF\nupstream nextjs {\n    server localhost:3000;\n}\n\nserver {\n    listen 80;\n    server_name $DOMAIN;\n    return 301 https://\\$server_name\\$request_uri;\n}\n\nserver {\n    listen 443 ssl http2;\n    server_name $DOMAIN;\n\n    # SSL Certificate Paths - Update these!\n    ssl_certificate /path/to/your/certificate.crt;\n    ssl_certificate_key /path/to/your/private.key;\n\n    ssl_protocols TLSv1.2 TLSv1.3;\n    ssl_ciphers HIGH:!aNULL:!MD5;\n    ssl_prefer_server_ciphers on;\n    ssl_session_cache shared:SSL:10m;\n    ssl_session_timeout 10m;\n\n    # Security Headers\n    add_header Strict-Transport-Security \"max-age=31536000\" always;\n    add_header X-Frame-Options \"SAMEORIGIN\" always;\n    add_header X-Content-Type-Options \"nosniff\" always;\n    add_header X-XSS-Protection \"1; mode=block\" always;\n\n    # Gzip Compression\n    gzip on;\n    gzip_types text/plain text/css application/json application/javascript;\n\n    location / {\n        proxy_pass http://nextjs;\n        proxy_http_version 1.1;\n        proxy_set_header Upgrade \\$http_upgrade;\n        proxy_set_header Connection 'upgrade';\n        proxy_set_header Host \\$host;\n        proxy_cache_bypass \\$http_upgrade;\n        proxy_set_header X-Real-IP \\$remote_addr;\n        proxy_set_header X-Forwarded-For \\$proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto \\$scheme;\n\n        # Timeouts\n        proxy_connect_timeout 60s;\n        proxy_send_timeout 60s;\n        proxy_read_timeout 60s;\n    }\n\n    location /api/ {\n        proxy_pass http://nextjs;\n        proxy_http_version 1.1;\n        proxy_set_header Host \\$host;\n        proxy_set_header X-Real-IP \\$remote_addr;\n        proxy_set_header X-Forwarded-For \\$proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto \\$scheme;\n\n        # Longer timeout for email operations\n        proxy_read_timeout 120s;\n        proxy_connect_timeout 120s;\n    }\n}\nEOF\n\necho -e \"${GREEN}✓${NC} Nginx config created\"\n\n# Enable site\nln -sf /etc/nginx/sites-available/tagneticai-email /etc/nginx/sites-enabled/ 2>/dev/null || true\n\n# Test Nginx config\nif nginx -t 2>&1 | grep -q \"successful\"; then\n    systemctl reload nginx\n    echo -e \"${GREEN}✓${NC} Nginx reloaded successfully\"\nelse\n    echo -e \"${YELLOW}⚠️  Nginx config test failed - check configuration${NC}\"\nfi\n\n# ============================================\n# Step 9: Summary\n# ============================================\necho -e \"\\n${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\"\necho -e \"${GREEN}✓ Deployment Complete!${NC}\"\necho -e \"${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\"\n\necho -e \"\\n${BLUE}📋 Next Steps:${NC}\"\necho -e \"  1. Edit .env with mail credentials:\"\necho -e \"     ${YELLOW}nano /opt/tagneticai-email/.env${NC}\"\necho -e \"\"\necho -e \"  2. Update SSL certificate in Nginx:\"\necho -e \"     ${YELLOW}nano /etc/nginx/sites-available/tagneticai-email${NC}\"\necho -e \"     Update: ssl_certificate and ssl_certificate_key paths\"\necho -e \"\"\necho -e \"  3. Check application status:\"\necho -e \"     ${YELLOW}pm2 status${NC}\"\necho -e \"\"\necho -e \"  4. View logs:\"\necho -e \"     ${YELLOW}pm2 logs tagneticai-email${NC}\"\necho -e \"\"\necho -e \"  5. Access your application:\"\necho -e \"     ${YELLOW}https://$DOMAIN${NC}\"\necho -e \"\"\necho -e \"${BLUE}📧 Mail Server Configuration:${NC}\"\necho -e \"  Host: (Your mail server hostname)\"\necho -e \"  IMAP Port: 993\"\necho -e \"  SMTP Port: 465\"\necho -e \"  User: (Your email address)\"\necho -e \"  Password: (Your email password)\"\necho -e \"\"\n\necho -e \"${BLUE}🆘 Troubleshooting:${NC}\"\necho -e \"  Check status: ${YELLOW}pm2 status${NC}\"\necho -e \"  View logs: ${YELLOW}pm2 logs${NC}\"\necho -e \"  Restart app: ${YELLOW}pm2 restart tagneticai-email${NC}\"\necho -e \"  Stop app: ${YELLOW}pm2 stop tagneticai-email${NC}\"\necho -e \"\"\n"