#!/usr/bin/env bash
# getmon — CLI tool untuk manajemen frontend dashboard getmon
# Usage:
#   getmon frontend start      # start server frontend
#   getmon frontend restart    # restart server frontend
#   getmon frontend stop       # stop server frontend
#   getmon frontend reload     # reload server frontend
#   getmon frontend status     # cek status server frontend
#   getmon help                # tampilkan help

set -euo pipefail

FRONTEND_DIR="/root/getmon/frontend"
FRONTEND_PORT="${GETMON_FRONTEND_PORT:-8000}"
PID_FILE="/tmp/getmon-frontend.pid"

# ── Helper ──────────────────────────────────────────────
log()  { echo "[getmon] $*"; }
error() { echo "[getmon][ERROR] $*" >&2; }

is_running() {
    # Cek PID file
    if [[ -f "$PID_FILE" ]]; then
        local pid
        pid=$(cat "$PID_FILE")
        if kill -0 "$pid" 2>/dev/null; then
            return 0
        fi
        rm -f "$PID_FILE"
    fi
    # Cek port 8000 dipakai (misal dari systemd service)
    if ss -tlnp 2>/dev/null | grep -q ":8000 " 2>/dev/null; then
        # Cek apakah process pada port 8000 milik kita
        local pid_port
        pid_port=$(ss -tlnp 2>/dev/null | grep ":8000 " | grep python3 | awk '{print $NF}' | grep -oP 'pid=\K[0-9]+' | head -1)
        if [[ -n "$pid_port" ]] && kill -0 "$pid_port" 2>/dev/null; then
            echo "$pid_port" > "$PID_FILE"
            return 0
        fi
    fi
    return 1
}

get_pid() {
    if [[ -f "$PID_FILE" ]]; then
        cat "$PID_FILE"
    fi
}

# ── start ──────────────────────────────────────────────
cmd_start() {
    if is_running; then
        echo "[getmon] Server frontend sudah berjalan (PID: $(get_pid))"
        return 0
    fi
    # Cek port 8000 sudah dipakai?
    if ss -tlnp 2>/dev/null | grep -q ":8000 " 2>/dev/null; then
        echo "[getmon][ERROR] Port 8000 sudah dipakai oleh process lain."
        echo "[getmon] Mungkin service systemd sudah aktif."
        echo "[getmon] Coba: sudo systemctl restart getmon-frontend"
        return 1
    fi
    echo "[getmon] Starting frontend server on port $FRONTEND_PORT..."
    cd "$FRONTEND_DIR"
    nohup python3 -m http.server "$FRONTEND_PORT" --directory "$FRONTEND_DIR" >/tmp/getmon-frontend.log 2>&1 &
    local pid=$!
    echo "$pid" > "$PID_FILE"
    sleep 1
    if kill -0 "$pid" 2>/dev/null; then
        echo "[getmon] Frontend server started (PID: $pid) — http://localhost:$FRONTEND_PORT"
    else
        echo "[getmon][ERROR] Gagal start server frontend"
        rm -f "$PID_FILE"
        return 1
    fi
}

# ── stop ───────────────────────────────────────────────
cmd_stop() {
    if ! is_running; then
        log "Server frontend belum berjalan"
        return 0
    fi
    local pid
    pid=$(get_pid)
    log "Stopping frontend server (PID: $pid)..."
    kill "$pid" 2>/dev/null || true
    sleep 1
    if kill -0 "$pid" 2>/dev/null; then
        kill -9 "$pid" 2>/dev/null || true
    fi
    rm -f "$PID_FILE"
    log "Frontend server stopped"
}

# ── restart / reload ────────────────────────────────────
cmd_restart() {
    cmd_stop
    sleep 1
    cmd_start
}

cmd_reload() {
    cmd_restart
}

# ── status ─────────────────────────────────────────────
cmd_status() {
    if is_running; then
        echo "Frontend server: RUNNING"
        echo "Port:          $FRONTEND_PORT"
        echo "PID:           $(get_pid)"
        echo "Directory:     $FRONTEND_DIR"
        echo "Log:           /tmp/getmon-frontend.log"
        return 0
    else
        echo "Frontend server: STOPPED"
        return 1
    fi
}

# ── help ───────────────────────────────────────────────
cmd_help() {
    cat << EOF
getmon — CLI untuk manajemen frontend dashboard getmon

USAGE:
  getmon frontend <command>

COMMANDS:
  start       Start the frontend server
  stop        Stop the frontend server
  restart     Restart the frontend server
  reload      Reload (restart) the frontend server
  status      Show frontend server status
  help        Show this help message

EXAMPLES:
  getmon frontend start
  getmon frontend status
  getmon frontend restart

ENVIRONMENT:
  GETMON_FRONTEND_PORT    Port untuk frontend (default: 8000)
EOF
}

# ── Dispatch ───────────────────────────────────────────
main() {
    local cmd="$1"
    local subcmd="${2:-}"

    case "$cmd" in
        frontend)
            case "$subcmd" in
                start)    cmd_start ;;
                stop)     cmd_stop ;;
                restart)  cmd_restart ;;
                reload)   cmd_reload ;;
                status)   cmd_status ;;
                help)     cmd_help ;;
                *)        error "Unknown frontend command: $subcmd (use 'getmon frontend help')"; cmd_help; exit 1 ;;
            esac
            ;;
        *)
            error "Unknown command: $cmd"
            cmd_help
            exit 1
            ;;
    esac
}

main "$@"
