#!/bin/bash
# ================================================================
# Nexus 6.0 — Upgrade Script
#
# Usage:
#   sudo bash upgrade.sh                          # auto-detect deploy dir
#   sudo bash upgrade.sh --deploy-dir /opt/nexus   # specify deploy dir
#
# Safe: git pull + pip install + restart. Database is NOT touched.
# ================================================================

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info()  { echo -e "${GREEN}[INFO]${NC} $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; }

DEPLOY_DIR=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --deploy-dir) DEPLOY_DIR="$2"; shift 2 ;;
        -h|--help)
            echo "Usage: sudo bash upgrade.sh [--deploy-dir PATH]"
            exit 0 ;;
        *) shift ;;
    esac
done

# Auto-detect deploy directory
if [ -z "$DEPLOY_DIR" ]; then
    # Check common locations
    for d in /opt/nexus /www/wwwroot/*/; do
        if [ -d "$d/server" ] && [ -d "$d/web" ]; then
            DEPLOY_DIR="$d"
            break
        fi
    done
    # Try from Supervisor config
    if [ -z "$DEPLOY_DIR" ]; then
        DEPLOY_DIR=$(supervisorctl status nexus 2>/dev/null | grep -oP 'cwd=\K[^ ,]+' || true)
    fi
fi

if [ -z "$DEPLOY_DIR" ] || [ ! -d "$DEPLOY_DIR/server" ]; then
    error "Cannot find Nexus installation. Use --deploy-dir to specify."
    exit 1
fi

VENV_DIR="$DEPLOY_DIR/venv"
ENV_FILE="$DEPLOY_DIR/.env"

echo ""
echo "=========================================="
echo "  Nexus 6.0 Upgrade"
echo "=========================================="
echo "  Deploy: $DEPLOY_DIR"
echo ""

# 1. Pull latest code
info "Step 1/4: Updating source code..."
if [ -d "$DEPLOY_DIR/.git" ]; then
    cd "$DEPLOY_DIR"
    OLD_REV=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
    git pull --ff-only 2>/dev/null || {
        error "git pull failed. You may have local changes."
        error "Resolve conflicts manually: cd $DEPLOY_DIR && git status"
        exit 1
    }
    NEW_REV=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
    if [ "$OLD_REV" = "$NEW_REV" ]; then
        info "  Already up to date (no new commits)"
    else
        info "  Updated: ${OLD_REV:0:8}..${NEW_REV:0:8}"
    fi
else
    warn "  Not a git repo. Skip git pull (update files manually)"
fi

# 2. Update Python dependencies
info "Step 2/4: Updating Python dependencies..."
if [ -d "$VENV_DIR/bin" ]; then
    "$VENV_DIR/bin/pip" install -q --upgrade pip
    "$VENV_DIR/bin/pip" install -q -r "$DEPLOY_DIR/requirements.txt" 2>/dev/null || {
        warn "  pip install had some warnings, but continuing..."
    }
else
    error "  venv not found at $VENV_DIR. Run install.sh first."
    exit 1
fi

# 3. Restart application
info "Step 3/4: Restarting Nexus..."
supervisorctl restart nexus >/dev/null 2>&1 || {
    warn "  supervisorctl restart failed. Try manually: supervisorctl restart nexus"
}

# 4. Health check
info "Step 4/4: Verifying health..."

# Read port from .env or default
PORT=8600
if [ -f "$ENV_FILE" ]; then
    PORT_FROM_ENV=$(grep '^NEXUS_PORT=' "$ENV_FILE" 2>/dev/null | cut -d'=' -f2 || true)
    [ -n "$PORT_FROM_ENV" ] && PORT="$PORT_FROM_ENV"
fi

HEALTH_OK=false
for i in $(seq 1 15); do
    if curl -sf "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then
        HEALTH_OK=true
        break
    fi
    sleep 2
done

echo ""
if [ "$HEALTH_OK" = true ]; then
    echo -e "  ${GREEN}Upgrade complete! Nexus is healthy.${NC}"
else
    echo -e "  ${YELLOW}Health check pending. Verify manually:${NC}"
    echo "    curl http://127.0.0.1:$PORT/health"
    echo "    supervisorctl status nexus"
fi
echo ""
