#!/bin/bash
# Deploy Universal HACCPro Installer to Your Server
# Run this on your local machine

set -e

SERVER="162.55.46.86"
SERVER_USER="root"

echo "🚀 Deploying Universal HACCPro Installer"
echo "========================================"

# Step 1: Upload the universal installer
echo "📤 Uploading universal installer..."

# Assuming the universal installer is saved as universal-haccpro-installer.sh
if [ ! -f "universal-haccpro-installer.sh" ]; then
    echo "❌ universal-haccpro-installer.sh not found"
    echo "💡 Save the universal installer script as 'universal-haccpro-installer.sh' first"
    exit 1
fi

# Upload to server (keeping old nginx path for compatibility, but API endpoint is now preferred)
scp universal-haccpro-installer.sh $SERVER_USER@$SERVER:/opt/haccpro/app/install-sensor.sh

echo "✅ Universal installer uploaded"

# Step 2: Update nginx configuration (if needed)
echo "⚙️ Updating nginx configuration..."

ssh $SERVER_USER@$SERVER << 'REMOTE_COMMANDS'

# Ensure the installer endpoint exists
if ! grep -q "/install/sensor" /etc/nginx/sites-available/haccpro; then
    # Add installer endpoint
    sed -i '/^}$/i\
\
    # HACCPro Universal Sensor Installer\
    location /install/sensor {\
        alias /var/www/haccpro/install/sensor.sh;\
        add_header Content-Type "text/plain; charset=utf-8";\
        add_header Cache-Control "no-cache, no-store, must-revalidate";\
        add_header Access-Control-Allow-Origin "*";\
    }\
\
    location /install/ {\
        alias /var/www/haccpro/install/;\
        autoindex on;\
        add_header Access-Control-Allow-Origin "*";\
    }' /etc/nginx/sites-available/haccpro

    # Test and reload nginx
    nginx -t && systemctl reload nginx
    echo "✅ Nginx configuration updated"
else
    echo "✅ Nginx configuration already exists"
fi

REMOTE_COMMANDS

# Step 3: Test the installer endpoint
echo "🧪 Testing installer endpoint..."

sleep 2

response=$(curl -s -w "%{http_code}" -o /tmp/test_universal_installer "https://api.haccpro.nl/v1/install/sensor" || echo "000")

if [[ "$response" == "200" ]]; then
    echo "✅ Universal installer endpoint working"

    # Check content
    if grep -q "Universal HACCPro" /tmp/test_universal_installer; then
        echo "✅ Universal installer content verified"

        # Show supported Pi models
        echo "🤖 Supported Pi Models:"
        grep -o "Pi [A-Za-z0-9]*" /tmp/test_universal_installer | sort -u | sed 's/^/  - /'

        script_size=$(wc -c < /tmp/test_universal_installer)
        echo "📏 Script size: $script_size bytes"
    else
        echo "⚠️ Warning: Unexpected content"
    fi
else
    echo "❌ Installer endpoint failed (HTTP $response)"
    exit 1
fi

# Step 4: Create customer materials
echo "📚 Creating customer materials..."

# Simple customer instructions
cat > customer-instructions.md << 'INSTRUCTIONS_EOF'
# 🤖 HACCPro Universal Temperature Sensor

## Works on ANY Raspberry Pi Model
✅ Pi Zero, Zero 2W
✅ Pi 3, Pi 4, Pi 5
✅ Future Pi models

Auto-detects your hardware and optimizes automatically!

## Super Simple Installation

### Step 1: Run One Command
```bash
curl -sSL https://api.haccpro.nl/v1/install/sensor | sudo bash
```

**Note**: Type `Y` when prompted to continue installation.

### Step 2: Configure with Automatic API Key
The installer will automatically generate an API key during configuration.
```bash
sudo haccpro-configure
```
Choose option 2 for automatic API key generation, or get a key from the dashboard.

### Step 3: Start Monitoring
```bash
sudo systemctl start haccpro-sensor
```

## What You Get
- 🌡️ Professional temperature monitoring
- 📧 Automatic email alerts
- 📊 Real-time dashboard
- 🔧 Hardware-optimized performance
- 📱 Mobile access
- 🛡️ HACCP compliance ready

## Hardware Requirements
- **Any Raspberry Pi** (Zero, 3, 4, 5, or future)
- **DS18B20 sensor** (waterproof recommended)
- **4.7kΩ resistor**
- **Internet connection** (WiFi or Ethernet)

## Wiring (Same for All Pi Models)
```
DS18B20          Raspberry Pi
-------          ------------
Red (VCC)    →   Pin 1 (3.3V)
Black (GND)  →   Pin 6 (Ground)
Yellow (Data)→   Pin 7 (GPIO4)

Connect 4.7kΩ resistor between Red and Yellow wires
```

## Support
- Dashboard: https://haccpro.nl
- Email: support@haccpro.nl
- Phone: (555) 123-4567

**Professional HACCP compliance in 5 minutes!** 🚀
INSTRUCTIONS_EOF

# Upload customer materials
scp customer-instructions.md $SERVER_USER@$SERVER:/var/www/haccpro/install/

# Hardware comparison chart
cat > pi-comparison.md << 'COMPARISON_EOF'
# HACCPro Sensor Performance by Pi Model

| Pi Model | Memory | Cores | HACCPro Performance | Recommended Use |
|----------|--------|-------|-------------------|-----------------|
| **Pi Zero** | 512MB | 1 | ✅ Excellent | Single sensor, low cost |
| **Pi Zero 2W** | 512MB | 4 | ✅ Excellent | Single sensor, WiFi built-in |
| **Pi 3** | 1GB | 4 | ✅ Excellent | Multiple sensors, robust |
| **Pi 4** | 1-8GB | 4 | ✅ Excellent | Multi-sensor, future-proof |
| **Pi 5** | 4-8GB | 4 | ✅ Excellent | High-performance, advanced features |

## Auto-Optimization Features

### Pi Zero/Zero 2W Optimizations
- 2-minute reading intervals (battery friendly)
- Reduced logging (SD card friendly)
- 100 offline reading storage
- Low CPU priority
- 60MB memory limit

### Pi 3/4 Standard Settings
- 1-minute reading intervals
- Standard logging
- 1000 offline reading storage
- Normal CPU priority
- 200MB memory limit

### Pi 5+ High Performance
- 30-second reading intervals
- Debug logging available
- 2000+ offline reading storage
- High CPU priority
- 300MB memory limit

**All models get the same features - just optimized for their capabilities!**
COMPARISON_EOF

scp pi-comparison.md $SERVER_USER@$SERVER:/var/www/haccpro/install/

# Cleanup local files
rm -f /tmp/test_universal_installer customer-instructions.md pi-comparison.md

echo
echo "🎉 Universal Installer Deployment Complete!"
echo "=========================================="
echo
echo "✅ Universal installer: https://api.haccpro.nl/v1/install/sensor"
echo "✅ Customer guide: https://haccpro.nl/install/customer-instructions.md"
echo "✅ Pi comparison: https://haccpro.nl/install/pi-comparison.md"
echo
echo "🎯 Customer Installation Command (Works on ANY Pi):"
echo "   curl -sSL https://api.haccpro.nl/v1/install/sensor | sudo bash"
echo
echo "🤖 Supported Hardware:"
echo "   ✅ Raspberry Pi Zero, Zero 2W"
echo "   ✅ Raspberry Pi 3, 4, 5"
echo "   ✅ Future Raspberry Pi models"
echo "   ✅ Auto-detects and optimizes automatically"
echo
echo "📋 What Happens on Each Pi:"
echo "   • Detects hardware specifications"
echo "   • Optimizes performance settings"
echo "   • Configures appropriate resource limits"
echo "   • Sets hardware-specific intervals"
echo "   • Creates optimized systemd service"
echo
echo "🚀 Ready for customers! Test on any Pi model:"
echo "   1. Get any Raspberry Pi"
echo "   2. Run: curl -sSL https://api.haccpro.nl/v1/install/sensor | sudo bash"
echo "   3. Configure: sudo haccpro-configure"
echo "   4. Start: sudo systemctl start haccpro-sensor"
echo
echo "💡 The same installer works perfectly on Pi Zero through Pi 5!"