#!/bin/sh
# EPOD ADT MCP server, standalone mode (macOS).
#
# Commands: epod-adt help
#
# The server runs as an own application on the runtime of the installed ADT for
# VS Code extension. The script never changes a file of the extension. The
# script never prints the bearer token. The token is in <home>/token and in
# <home>/mcp-client.json, both with mode 600. Only "epod-adt token" shows it, and
# only in an interactive terminal.
#
# The commands start, stop, and install hold <home>/start.lock while they work.
# A Java helper takes the lock (run-locked), because the stdio shim takes the
# same Java file lock. The internal commands __start, __stop, and __install do
# the work inside the lock.

set -u

HOME_DIR="${EPOD_ADT_HOME:-$HOME/.epod-adt}"
EXT_DIR="${EPOD_VSCODE_EXTENSIONS:-$HOME/.vscode/extensions}"
PID_FILE="$HOME_DIR/epod-adt.pid"
STOP_FILE="$HOME_DIR/stop"
LOG_DIR="$HOME_DIR/logs"
CLIENT_FILE="$HOME_DIR/mcp-client.json"
START_TIMEOUT=120
STOP_TIMEOUT=60
CLI_CLASS=com.epod.adt.mcp.standalone.cli.Cli
JVM_OPTS="-XX:+UseSerialGC -XX:TieredStopAtLevel=1"
SCRIPT="$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0")"
# The SNC variables of the SSO logon. The server inherits the environment of the
# process that starts it. A client can start the server with a short allow list
# of variables (Codex does), so __start fills each empty variable first.
SNC_VARS="SNC_LIB SNC_LIB_64 SECUDIR"

die() {
    echo "epod-adt: $*" >&2
    exit 1
}

# Prints the port of epod.properties. The default is 3100.
read_port() {
    port=3100
    if [ -f "$HOME_DIR/epod.properties" ]; then
        p=$(sed -n 's/^[[:space:]]*port[[:space:]]*[=:][[:space:]]*\([0-9][0-9]*\)[[:space:]]*$/\1/p' \
            "$HOME_DIR/epod.properties" | tail -n 1)
        [ -n "$p" ] && port=$p
    fi
    echo "$port"
}

# Prints the PID of the PID file when that process runs.
running_pid() {
    [ -f "$PID_FILE" ] || return 1
    pid=$(cat "$PID_FILE" 2>/dev/null)
    [ -n "$pid" ] || return 1
    kill -0 "$pid" 2>/dev/null || return 1
    echo "$pid"
}

# Prints the HTTP status of GET /health.
health() {
    curl -s -o /dev/null -m 2 -w '%{http_code}' "http://127.0.0.1:$1/health" 2>/dev/null
}

# Prints the PID of the process that listens on the port.
listener_pid() {
    lsof -nP -iTCP:"$1" -sTCP:LISTEN -t 2>/dev/null | head -n 1
}

# Prints the java of the JRE of an installed ADT for VS Code extension. The
# config generator then selects the newest extension.
find_java() {
    for ext in "$EXT_DIR"/sapse.adt-vscode-*; do
        for j in "$ext"/adt-ls/macosx/cocoa/*/Adt-ls.app/Contents/Eclipse/plugins/com.sap.adt.jvm.sapmachineminimal.*/jre/bin/java; do
            if [ -x "$j" ]; then
                echo "$j"
                return 0
            fi
        done
    done
    return 1
}

# Prints the Gson jar in the plugins folder of the JRE.
find_gson() {
    plugins=$(dirname "$(dirname "$(dirname "$(dirname "$1")")")")
    for g in "$plugins"/com.google.gson_*.jar; do
        if [ -f "$g" ]; then
            echo "$g"
            return 0
        fi
    done
    return 1
}

# Prints the newest standalone jar in the plugins folder of the home.
find_standalone_jar() {
    jar=$(ls "$HOME_DIR"/plugins/com.epod.adt.mcp.standalone_*.jar 2>/dev/null | sort | tail -n 1)
    [ -n "$jar" ] || return 1
    echo "$jar"
}

# Prints the class path of the Java commands: the standalone jar, the core jar
# (both in the folder $1), and the Gson jar $2.
cli_classpath() {
    sa=$(ls "$1"/com.epod.adt.mcp.standalone_*.jar 2>/dev/null | sort | tail -n 1)
    core=$(ls "$1"/com.epod.adt.mcp.core_*.jar 2>/dev/null | sort | tail -n 1)
    [ -n "$sa" ] && [ -n "$core" ] || return 1
    echo "$sa:$core:$2"
}

# Sets JAVA and CP for the Java commands, or stops with a clear text.
need_cli() {
    JAVA=$(find_java) || die "The ADT for VS Code extension is not installed. No folder sapse.adt-vscode-* with a JRE in $EXT_DIR."
    gson=$(find_gson "$JAVA") || die "The ADT for VS Code extension has no com.google.gson jar next to $JAVA."
    CP=$(cli_classpath "$HOME_DIR/plugins" "$gson") || die "No EPOD jars in $HOME_DIR/plugins. Run: epod-adt install <folder of the unpacked zip>"
}

# Runs a Java command and returns its exit code.
run_cli() {
    need_cli
    "$JAVA" $JVM_OPTS -cp "$CP" "$CLI_CLASS" --home "$HOME_DIR" "$@"
}

# Runs the internal command "$@" of this script while a Java helper holds
# start.lock. The jars come from the folder $JAR_DIR. Without a JRE or without
# jars the command runs with no lock. No shim can run without them.
run_locked() {
    if j=$(find_java) && g=$(find_gson "$j") && cp=$(cli_classpath "$JAR_DIR" "$g"); then
        exec "$j" $JVM_OPTS -cp "$cp" "$CLI_CLASS" --home "$HOME_DIR" run-locked -- /bin/sh "$SCRIPT" "$@"
    fi
    exec /bin/sh "$SCRIPT" "$@"
}

# Fills each empty SNC variable from the launchd user environment, which a GUI
# app such as VS Code also gets. Prints the names of the filled variables, never
# their values.
complete_snc_env() {
    command -v launchctl >/dev/null 2>&1 || return 0
    filled=""
    for v in $SNC_VARS; do
        eval "current=\${$v:-}"
        if [ -z "$current" ]; then
            value=$(launchctl getenv "$v" 2>/dev/null)
            if [ -n "$value" ]; then
                export "$v=$value"
                filled="$filled $v"
            fi
        fi
    done
    if [ -n "$filled" ]; then
        echo "The launcher filled these variables from the launchd environment:$filled"
    fi
}

running_text() {
    echo "EPOD ADT MCP server runs on http://127.0.0.1:$1/mcp (PID $2). Client configuration: $CLIENT_FILE"
}

stdio_text() {
    echo "Client entry (stdio): $HOME_DIR/epod-adt stdio"
}

cmd_install() {
    src="${1:-$(cd "$(dirname "$0")" && pwd)}"
    JAR_DIR="$src/plugins"
    run_locked __install "$src"
}

do_install() {
    src="$1"
    [ -d "$src/plugins" ] || die "The folder $src has no plugins folder. Give the folder of the unpacked zip."
    src_abs=$(cd "$src" && pwd -P)
    mkdir -p "$HOME_DIR" || die "The folder $HOME_DIR cannot be created."
    home_abs=$(cd "$HOME_DIR" && pwd -P)
    [ "$src_abs" != "$home_abs" ] || die "The folder $src is the installation. Give the folder of the unpacked zip."
    if pid=$(running_pid); then
        die "The server runs (PID $pid). Run: epod-adt stop"
    fi
    ls "$src"/plugins/com.epod.adt.mcp.core_*.jar >/dev/null 2>&1 || die "The folder $src/plugins has no core jar."
    ls "$src"/plugins/com.epod.adt.mcp.standalone_*.jar >/dev/null 2>&1 || die "The folder $src/plugins has no standalone jar."
    mkdir -p "$HOME_DIR/plugins" "$LOG_DIR" || die "The folder $HOME_DIR/plugins cannot be created."
    chmod 700 "$HOME_DIR"
    rm -f "$HOME_DIR"/plugins/com.epod.adt.mcp.core_*.jar "$HOME_DIR"/plugins/com.epod.adt.mcp.standalone_*.jar
    cp "$src"/plugins/com.epod.adt.mcp.core_*.jar "$src"/plugins/com.epod.adt.mcp.standalone_*.jar "$HOME_DIR/plugins/" \
        || die "The jars cannot be copied to $HOME_DIR/plugins."
    for f in epod-adt epod-adt.ps1 epod-adt.cmd README.md; do
        [ -f "$src/$f" ] && cp "$src/$f" "$HOME_DIR/$f"
    done
    chmod 755 "$HOME_DIR/epod-adt"
    echo "EPOD ADT MCP server installed in $HOME_DIR:"
    ls -1 "$HOME_DIR/plugins" | sed 's/^/  plugins\//'
    echo "Start it with: $HOME_DIR/epod-adt start"
    echo "Add it to a client with: $HOME_DIR/epod-adt install-claude (or install-codex)"
}

do_start() {
    mkdir -p "$LOG_DIR" || die "The folder $LOG_DIR cannot be created."
    chmod 700 "$HOME_DIR"
    port=$(read_port)
    if pid=$(running_pid); then
        if [ "$(health "$port")" = "200" ]; then
            running_text "$port" "$pid"
            return 0
        fi
        die "The process $pid of $PID_FILE runs, but port $port does not answer. Run: epod-adt stop"
    fi
    lp=$(listener_pid "$port")
    [ -z "$lp" ] || die "Port $port is in use by PID $lp. Set another port in $HOME_DIR/epod.properties."

    java=$(find_java) || die "The ADT for VS Code extension is not installed. No folder sapse.adt-vscode-* with a JRE in $EXT_DIR."
    gson=$(find_gson "$java") || die "The ADT for VS Code extension has no com.google.gson jar next to $java."
    jar=$(find_standalone_jar) || die "No com.epod.adt.mcp.standalone_<version>.jar in $HOME_DIR/plugins. Run: epod-adt install <folder of the unpacked zip>"
    case "$(uname -m)" in
        arm64|aarch64) arch=aarch64 ;;
        *) arch=x86_64 ;;
    esac

    out=$("$java" -cp "$jar:$gson" com.epod.adt.mcp.standalone.launch.ConfigGenerator \
        --home "$HOME_DIR" --os macosx --arch "$arch" --extensions "$EXT_DIR" 2>"$LOG_DIR/generator.err")
    rc=$?
    [ $rc -eq 0 ] || die "$(cat "$LOG_DIR/generator.err")"
    launcher=$(echo "$out" | sed -n 's/^launcher=//p')
    [ -x "$launcher" ] || die "The launcher executable $launcher does not exist."

    complete_snc_env
    rm -f "$STOP_FILE"
    # The server gets no handle of the caller: stdin from /dev/null, stdout and
    # stderr to console.log. It runs in a new session, so it leaves the process
    # group and the terminal of the caller. A caller that reads this script
    # through a pipe then gets the end of the pipe when this script ends.
    (
        cd "$HOME_DIR" || exit 1
        if [ -x /usr/bin/perl ]; then
            /usr/bin/perl -MPOSIX -e 'POSIX::setsid() >= 0 or die "setsid: $!\n"; exec { $ARGV[0] } @ARGV or die "exec: $!\n"' \
                -- "$launcher" -configuration "$HOME_DIR/configuration" -data "$HOME_DIR/workspace" \
                >"$LOG_DIR/console.log" 2>&1 </dev/null &
        else
            echo "No /usr/bin/perl. The server runs in the session of the caller." >"$LOG_DIR/console.log"
            nohup "$launcher" -configuration "$HOME_DIR/configuration" -data "$HOME_DIR/workspace" \
                >>"$LOG_DIR/console.log" 2>&1 </dev/null &
        fi
        echo $! >"$PID_FILE"
    )
    pid=$(cat "$PID_FILE")
    i=0
    while [ $i -lt $START_TIMEOUT ]; do
        if ! kill -0 "$pid" 2>/dev/null; then
            rm -f "$PID_FILE"
            echo "epod-adt: The server process ended during the start. The last lines of $LOG_DIR/console.log:" >&2
            tail -n 20 "$LOG_DIR/console.log" >&2
            exit 1
        fi
        if [ "$(health "$port")" = "200" ]; then
            running_text "$port" "$pid"
            return 0
        fi
        sleep 1
        i=$((i + 1))
    done
    echo "epod-adt: The server did not answer on port $port within $START_TIMEOUT seconds. PID $pid runs. The last lines of $LOG_DIR/console.log:" >&2
    tail -n 20 "$LOG_DIR/console.log" >&2
    exit 1
}

do_stop() {
    port=$(read_port)
    if ! pid=$(running_pid); then
        rm -f "$PID_FILE"
        echo "EPOD ADT MCP server is not running."
        return 0
    fi
    : >"$STOP_FILE"
    i=0
    while kill -0 "$pid" 2>/dev/null; do
        if [ $i -ge $STOP_TIMEOUT ]; then
            die "The server did not stop within $STOP_TIMEOUT seconds. PID $pid still runs. End it with: kill $pid"
        fi
        sleep 1
        i=$((i + 1))
    done
    rm -f "$PID_FILE" "$STOP_FILE"
    lp=$(listener_pid "$port")
    [ -z "$lp" ] || die "The server stopped, but port $port is in use by PID $lp."
    echo "EPOD ADT MCP server stopped (PID $pid). Port $port is free."
}

cmd_status() {
    port=$(read_port)
    if pid=$(running_pid); then
        if [ "$(health "$port")" = "200" ]; then
            running_text "$port" "$pid"
        else
            echo "EPOD ADT MCP server process $pid runs, but port $port does not answer."
        fi
        stdio_text
        return 0
    fi
    echo "EPOD ADT MCP server is stopped."
    stdio_text
    echo "Client configuration (HTTP): $CLIENT_FILE"
    return 3
}

# The stdio entry of an MCP client. Java replaces the shell, so the client talks
# to the shim directly. This branch writes nothing to stdout.
cmd_stdio() {
    JAVA=$(find_java) || die "The ADT for VS Code extension is not installed. No folder sapse.adt-vscode-* with a JRE in $EXT_DIR."
    gson=$(find_gson "$JAVA") || die "The ADT for VS Code extension has no com.google.gson jar next to $JAVA."
    CP=$(cli_classpath "$HOME_DIR/plugins" "$gson") || die "No EPOD jars in $HOME_DIR/plugins. Run: epod-adt install <folder of the unpacked zip>"
    exec "$JAVA" $JVM_OPTS -cp "$CP" "$CLI_CLASS" --home "$HOME_DIR" stdio
}

# Adds the stdio entry epod-adt to Claude Code ($1 = claude) or Codex ($1 = codex).
# The entry is a command. It holds no URL and no token.
cmd_install_client() {
    client=$1
    entry="$HOME_DIR/epod-adt"
    if [ "$client" = claude ]; then
        name="Claude Code (claude)"
        if [ -n "${EPOD_ADT_HOME:-}" ]; then
            manual="claude mcp add epod-adt --scope user -e \"EPOD_ADT_HOME=$HOME_DIR\" -- \"$entry\" stdio"
        else
            manual="claude mcp add epod-adt --scope user -- \"$entry\" stdio"
        fi
    else
        name="Codex (codex)"
        if [ -n "${EPOD_ADT_HOME:-}" ]; then
            manual="codex mcp add epod-adt --env \"EPOD_ADT_HOME=$HOME_DIR\" -- \"$entry\" stdio"
        else
            manual="codex mcp add epod-adt -- \"$entry\" stdio"
        fi
    fi
    if ! command -v "$client" >/dev/null 2>&1; then
        echo "epod-adt: $name is not on the PATH. Run this command after you install it:" >&2
        echo "  $manual" >&2
        exit 1
    fi
    [ -x "$entry" ] || die "The file $entry does not exist. Run: epod-adt install <folder of the unpacked zip>"
    if [ "$client" = claude ]; then
        claude mcp remove epod-adt --scope user >/dev/null 2>&1
        if [ -n "${EPOD_ADT_HOME:-}" ]; then
            claude mcp add epod-adt --scope user -e "EPOD_ADT_HOME=$HOME_DIR" -- "$entry" stdio
        else
            claude mcp add epod-adt --scope user -- "$entry" stdio
        fi || die "claude mcp add failed. Run the command by hand: $manual"
        echo "Claude Code entry epod-adt added (user scope). The entry starts EPOD with: $entry stdio. The entry holds no token."
    else
        codex mcp remove epod-adt >/dev/null 2>&1
        if [ -n "${EPOD_ADT_HOME:-}" ]; then
            codex mcp add epod-adt --env "EPOD_ADT_HOME=$HOME_DIR" -- "$entry" stdio
        else
            codex mcp add epod-adt -- "$entry" stdio
        fi || die "codex mcp add failed. Run the command by hand: $manual"
        echo "Codex entry epod-adt added. The entry starts EPOD with: $entry stdio. The entry holds no token."
    fi
}

# The live screen. The terminal gets single-key input with no echo while Java
# runs. The trap restores the terminal mode also after Ctrl-C.
cmd_monitor() {
    for a in "$@"; do
        [ "$a" = "--snapshot" ] && { run_cli monitor "$@"; exit $?; }
    done
    if [ ! -t 0 ] || [ ! -t 1 ]; then
        run_cli monitor "$@"
        exit $?
    fi
    need_cli
    saved=$(stty -g)
    trap 'stty "$saved"' EXIT
    trap 'stty "$saved"; exit 130' INT TERM
    size=$(stty size 2>/dev/null)
    LINES=${size% *}
    COLUMNS=${size#* }
    export LINES COLUMNS
    stty -icanon -echo min 1 time 0
    "$JAVA" $JVM_OPTS -cp "$CP" "$CLI_CLASS" --home "$HOME_DIR" monitor "$@"
    rc=$?
    stty "$saved"
    trap - EXIT INT TERM
    exit $rc
}

JAR_DIR="$HOME_DIR/plugins"
case "${1:-}" in
    install) shift; cmd_install "$@" ;;
    start) run_locked __start ;;
    stop) run_locked __stop ;;
    status) cmd_status ;;
    stdio) cmd_stdio ;;
    install-claude) cmd_install_client claude ;;
    install-codex) cmd_install_client codex ;;
    log|activity|mode|token|help) run_cli "$@"; exit $? ;;
    monitor) shift; cmd_monitor "$@" ;;
    __install) shift; do_install "$@" ;;
    __start) do_start ;;
    __stop) do_stop ;;
    *)
        echo "Usage: epod-adt install [<folder>] | start | stop | status | stdio | install-claude | install-codex" >&2
        echo "       | log [-f] [-n <lines>] | activity [-f] [-n <lines>] | mode [<id> read-only|write]" >&2
        echo "       | token [rotate] | monitor [--snapshot] | help" >&2
        exit 2
        ;;
esac
