#!/bin/bash
# ============================================================
# Collnetwork WiFi Portal - VPS Deployment Script
# Ubuntu 24.04 | Run as root: bash deploy.sh
# ============================================================

set -e   # Exit on any error

GREEN='\033[0;32m'
PURPLE='\033[0;35m'
RED='\033[0;31m'
NC='\033[0m'

log()  { echo -e "${GREEN}[✔]${NC} $1"; }
info() { echo -e "${PURPLE}[→]${NC} $1"; }
err()  { echo -e "${RED}[✘]${NC} $1"; exit 1; }

echo ""
echo -e "${PURPLE}================================================${NC}"
echo -e "${PURPLE}  Collnetwork WiFi Portal - Deployment Script  ${NC}"
echo -e "${PURPLE}================================================${NC}"
echo ""

# ── 1. Update System ──────────────────────────────────────
info "Updating system packages..."
apt-get update -qq && apt-get upgrade -y -qq
log "System updated"

# ── 2. Install Dependencies ───────────────────────────────
info "Installing Python, pip, and system packages..."
apt-get install -y -qq python3 python3-pip python3-venv \
    pkg-config default-libmysqlclient-dev build-essential \
    nginx curl git
log "Dependencies installed"

# ── 3. Setup MySQL Database ───────────────────────────────
info "Setting up MySQL database..."
if ! command -v mysql &>/dev/null; then
    err "MySQL is not installed. Please install MySQL first."
fi
mysql -u root -p < /opt/collnetwork/setup_db.sql
log "Database created: collnetwork_wifi"

# ── 4. Create App Directory ───────────────────────────────
info "Setting up application directory..."
mkdir -p /opt/collnetwork
mkdir -p /var/log/collnetwork

# Copy project files if running from source
cp -r /home/ubuntu/collnetwork/* /opt/collnetwork/ 2>/dev/null || true

chown -R www-data:www-data /opt/collnetwork
chown -R www-data:www-data /var/log/collnetwork
log "App directory ready at /opt/collnetwork"

# ── 5. Python Virtual Environment ─────────────────────────
info "Creating Python virtual environment..."
python3 -m venv /opt/collnetwork/venv
/opt/collnetwork/venv/bin/pip install --upgrade pip -q
/opt/collnetwork/venv/bin/pip install -r /opt/collnetwork/requirements.txt -q
log "Virtual environment ready"

# ── 6. Systemd Service ────────────────────────────────────
info "Installing systemd service..."
cp /opt/collnetwork/collnetwork.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable collnetwork
systemctl start collnetwork
log "Service started: collnetwork.service"

# ── 7. Nginx Reverse Proxy ────────────────────────────────
info "Configuring Nginx..."
cat > /etc/nginx/sites-available/collnetwork << 'EOF'
server {
    listen 80;
    server_name wifiregister.collnetwork.net 46.101.144.229;

    client_max_body_size 10M;

    location /static/ {
        alias /opt/collnetwork/static/;
        expires 30d;
    }

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 60s;
        proxy_read_timeout 60s;
    }
}
EOF

ln -sf /etc/nginx/sites-available/collnetwork /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx
log "Nginx configured"

# ── 8. Firewall ───────────────────────────────────────────
info "Configuring UFW firewall..."
ufw allow 22/tcp   >/dev/null 2>&1
ufw allow 80/tcp   >/dev/null 2>&1
ufw allow 443/tcp  >/dev/null 2>&1
ufw --force enable >/dev/null 2>&1
log "Firewall configured"

# ── 9. Status Check ───────────────────────────────────────
echo ""
echo -e "${PURPLE}================================================${NC}"
echo -e "${GREEN}  Deployment Complete!${NC}"
echo -e "${PURPLE}================================================${NC}"
echo ""
echo "  App URL   : http://wifiregister.collnetwork.net"
echo "  Register  : http://wifiregister.collnetwork.net/register"
echo "  Logs      : journalctl -u collnetwork -f"
echo "  Nginx log : tail -f /var/log/nginx/error.log"
echo ""
echo -e "${PURPLE}NEXT STEPS:${NC}"
echo "  1. Edit /opt/collnetwork/.env and add your real Paystack keys"
echo "  2. Copy your logo to /opt/collnetwork/static/img/collnetwork_logo.png"
echo "  3. Copy hotspot_login.html to your MikroTik (replace login.html)"
echo "  4. Add Paystack webhook URL in your Paystack dashboard:"
echo "     http://wifiregister.collnetwork.net/paystack/webhook"
echo "  5. Restart: systemctl restart collnetwork"
echo ""
systemctl status collnetwork --no-pager
