#!/bin/bash
# ============================================
# wepanel CLI — Manage your hosting panel
# Installed at /usr/local/bin/wepanel
# ============================================

set -e

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

PANEL_VERSION="0.1.0"
PANEL_DIR="/opt/wepanel"
CONFIG_DIR="/etc/wepanel"
LOG_DIR="/var/log/wepanel"
REPO_URL="https://git.wdpdev.co/wepanel/wepanel.git"
BUILD_DIR="/tmp/wepanel-build"

log_info()  { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn()  { echo -e "${YELLOW}[!]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_step()  { echo -e "\n${BLUE}==> $1${NC}"; }

require_root() {
    if [ "$(id -u)" -ne 0 ]; then
        log_error "This command requires root privileges. Use: sudo wepanel $1"
        exit 1
    fi
}

# ─── VERSION ───
cmd_version() {
    echo -e "${CYAN}wepanel${NC} v${PANEL_VERSION}"
    if [ -f "$PANEL_DIR/server" ]; then
        echo -e "  Backend:  $(stat -c '%y' "$PANEL_DIR/server" 2>/dev/null | cut -d. -f1)"
    fi
    if [ -f "$PANEL_DIR/frontend/server.js" ]; then
        echo -e "  Frontend: $(stat -c '%y' "$PANEL_DIR/frontend/server.js" 2>/dev/null | cut -d. -f1)"
    fi
}

# ─── STATUS ───
cmd_status() {
    echo -e "${CYAN}wepanel${NC} Service Status"
    echo ""
    for svc in wepanel wepanel-frontend wepanel-agent; do
        if systemctl is-active --quiet "$svc" 2>/dev/null; then
            echo -e "  ${GREEN}●${NC} $svc — running"
        else
            echo -e "  ${RED}●${NC} $svc — stopped"
        fi
    done
    echo ""

    # Show ports
    echo -e "  ${BLUE}Ports:${NC}"
    echo "    8080 — API Server"
    echo "    3000 — Frontend"
    echo "    8081 — License Server"
}

# ─── UPDATE ───
cmd_update() {
    require_root "update"

    echo -e "${CYAN}"
    echo "  _    _ _____  _____          _ "
    echo " | |  | | ____||  __ \\   /\\\\  | |"
    echo " | |  | |  _|  | |__) | /  \\\\ | |"
    echo " | |/\\| | |___ |  ___/ / /\\\\ \\\\| |"
    echo "  \\/  \\/|_____||_|    /_/  \\\\_\\_|"
    echo ""
    echo -e "  Update Manager${NC}"
    echo ""

    # Step 1: Download latest source
    log_step "Downloading latest version..."
    rm -rf "$BUILD_DIR"

    if command -v git &>/dev/null; then
        git clone --depth 1 "$REPO_URL" "$BUILD_DIR" 2>/dev/null || {
            log_error "Failed to clone repository"
            exit 1
        }
    else
        log_error "git is required. Install with: apt install git"
        exit 1
    fi

    # Step 2: Build backend
    log_step "Building backend..."
    cd "$BUILD_DIR/backend"

    if ! command -v go &>/dev/null; then
        log_error "Go is not installed. Run: wepanel install-go"
        exit 1
    fi

    go build -o "$PANEL_DIR/server.new" ./cmd/server/ || {
        log_error "Backend build failed"
        exit 1
    }
    log_info "Backend built successfully"

    # Step 3: Build frontend
    log_step "Building frontend..."
    cd "$BUILD_DIR/frontend"

    if ! command -v node &>/dev/null; then
        log_warn "Node.js not found, installing..."
        curl -fsSL https://deb.nodesource.com/setup_20.x | bash - >/dev/null 2>&1
        apt-get install -y nodejs >/dev/null 2>&1 || dnf install -y nodejs >/dev/null 2>&1
    fi

    npm install --production=false --silent 2>/dev/null || npm install --silent 2>/dev/null
    npm run build 2>/dev/null || {
        log_error "Frontend build failed"
        exit 1
    }
    log_info "Frontend built successfully"

    # Step 4: Stop services
    log_step "Stopping services..."
    systemctl stop wepanel 2>/dev/null || true
    systemctl stop wepanel-frontend 2>/dev/null || true

    # Step 5: Swap binaries
    log_step "Installing update..."

    # Backup current
    if [ -f "$PANEL_DIR/server" ]; then
        cp "$PANEL_DIR/server" "$PANEL_DIR/server.bak"
    fi

    # Install new backend binary
    mv "$PANEL_DIR/server.new" "$PANEL_DIR/server"
    chmod +x "$PANEL_DIR/server"

    # Install new frontend
    rm -rf "$PANEL_DIR/frontend.bak"
    if [ -d "$PANEL_DIR/frontend" ]; then
        mv "$PANEL_DIR/frontend" "$PANEL_DIR/frontend.bak"
    fi

    mkdir -p "$PANEL_DIR/frontend"
    cp -r "$BUILD_DIR/frontend/.next/standalone/." "$PANEL_DIR/frontend/"
    cp -r "$BUILD_DIR/frontend/.next/static" "$PANEL_DIR/frontend/.next/static"
    cp -r "$BUILD_DIR/frontend/public" "$PANEL_DIR/frontend/public" 2>/dev/null || true

    # Copy frontend env
    if [ -f "$CONFIG_DIR/frontend.env" ]; then
        cp "$CONFIG_DIR/frontend.env" "$PANEL_DIR/frontend/.env"
    fi

    log_info "Files installed"

    # Step 6: Run database migrations (automatic via Go server)
    log_step "Starting services..."
    systemctl start wepanel
    systemctl start wepanel-frontend

    # Verify
    sleep 2
    if systemctl is-active --quiet wepanel; then
        log_info "Backend — running ✓"
    else
        log_error "Backend failed to start! Rolling back..."
        cp "$PANEL_DIR/server.bak" "$PANEL_DIR/server"
        systemctl start wepanel
    fi

    if systemctl is-active --quiet wepanel-frontend; then
        log_info "Frontend — running ✓"
    else
        log_warn "Frontend service not found or failed — creating service..."
        setup_frontend_service
        systemctl start wepanel-frontend 2>/dev/null || true
    fi

    # Cleanup
    rm -rf "$BUILD_DIR"
    rm -f "$PANEL_DIR/server.bak"
    rm -rf "$PANEL_DIR/frontend.bak"

    echo ""
    echo -e "${GREEN}============================================${NC}"
    echo -e "${GREEN}  Update complete! ✓${NC}"
    echo -e "${GREEN}============================================${NC}"
    echo ""
    cmd_version
}

# ─── ROLLBACK ───
cmd_rollback() {
    require_root "rollback"

    if [ -f "$PANEL_DIR/server.bak" ]; then
        log_step "Rolling back backend..."
        systemctl stop wepanel 2>/dev/null || true
        mv "$PANEL_DIR/server.bak" "$PANEL_DIR/server"
        systemctl start wepanel
        log_info "Backend rolled back"
    else
        log_warn "No backend backup found"
    fi

    if [ -d "$PANEL_DIR/frontend.bak" ]; then
        log_step "Rolling back frontend..."
        systemctl stop wepanel-frontend 2>/dev/null || true
        rm -rf "$PANEL_DIR/frontend"
        mv "$PANEL_DIR/frontend.bak" "$PANEL_DIR/frontend"
        systemctl start wepanel-frontend 2>/dev/null || true
        log_info "Frontend rolled back"
    else
        log_warn "No frontend backup found"
    fi
}

# ─── RESTART ───
cmd_restart() {
    require_root "restart"
    log_step "Restarting wepanel..."
    systemctl restart wepanel
    systemctl restart wepanel-frontend 2>/dev/null || true
    systemctl restart wepanel-agent 2>/dev/null || true
    sleep 1
    cmd_status
}

# ─── LOGS ───
cmd_logs() {
    local svc="${1:-wepanel}"
    journalctl -u "$svc" -f --no-pager
}

# ─── SETUP FRONTEND SERVICE ───
setup_frontend_service() {
    cat > /etc/systemd/system/wepanel-frontend.service << 'EOF'
[Unit]
Description=wepanel Frontend
After=network.target wepanel.service

[Service]
Type=simple
WorkingDirectory=/opt/wepanel/frontend
Environment=NODE_ENV=production
Environment=PORT=3000
Environment=HOSTNAME=0.0.0.0
ExecStart=/usr/bin/node server.js
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable wepanel-frontend 2>/dev/null || true
}

# ─── HELP ───
cmd_help() {
    echo -e "${CYAN}wepanel${NC} — Hosting Panel Manager"
    echo ""
    echo "Usage: wepanel <command>"
    echo ""
    echo "Commands:"
    echo "  update       Download & install latest version"
    echo "  rollback     Revert to previous version"
    echo "  restart      Restart all wepanel services"
    echo "  status       Show service status"
    echo "  logs [svc]   View live logs (default: wepanel)"
    echo "  version      Show installed version"
    echo "  help         Show this help"
    echo ""
    echo "Examples:"
    echo "  sudo wepanel update       # Update to latest version"
    echo "  sudo wepanel restart      # Restart all services"
    echo "  wepanel logs              # View backend logs"
    echo "  wepanel logs wepanel-frontend  # View frontend logs"
}

# ─── MAIN ───
case "${1:-help}" in
    update)     cmd_update ;;
    rollback)   cmd_rollback ;;
    restart)    cmd_restart ;;
    status)     cmd_status ;;
    logs)       cmd_logs "$2" ;;
    version|-v) cmd_version ;;
    help|--help|-h) cmd_help ;;
    *)
        log_error "Unknown command: $1"
        cmd_help
        exit 1
    ;;
esac
