#!/bin/sh
# pomelo-ai-start: start / stop the local AI service (llama.cpp llama-server, OpenAI-compatible) -- only when the user asks for it.
#   pomelo-ai-start [start]   start the service in the background (does nothing if it already runs)
#   pomelo-ai-start stop      stop it (frees the model memory)
#   pomelo-ai-start restart
#   pomelo-ai-start status    one line: running/not running, port, model
# Nothing starts this at boot, and the image ships no model.  Settings: /etc/pomelo/ai.conf, then ~/.config/pomelo/ai.conf (the Pomelo
# assistant writes MODEL there when you pick a model file).  The files are only read (KEY=VALUE lines), never executed.
# The server always binds 127.0.0.1 (nothing in the config can change that).  No systemd, no tmux: plain POSIX sh (POSIX sh).
CONF_SYS=${POMELO_AI_CONF:-/etc/pomelo/ai.conf}
CONF_USER=${XDG_CONFIG_HOME:-${HOME:-/root}/.config}/pomelo/ai.conf
RT=${XDG_RUNTIME_DIR:-/tmp}
PIDF=$RT/pomelo-ai.pid; STF=$RT/pomelo-ai.status
CACHE=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/pomelo; LOG=$CACHE/ai.log

# conf KEY DEFAULT [sys-only]: last assignment wins (user file after the system file); quotes around the value are removed
conf() {
    v=$2
    files=$CONF_SYS; [ -n "$3" ] || files="$files $CONF_USER"
    for f in $files; do
        [ -r "$f" ] || continue
        x=$(sed -n "s/^[ 	]*$1=//p" "$f" 2>/dev/null | tail -n 1 | sed "s/^\"\(.*\)\"\$/\1/; s/^'\(.*\)'\$/\1/; s/[ 	]*\$//")
        [ -n "$x" ] && v=$x
    done
    printf '%s' "$v"
}

fail() { mkdir -p "$RT" 2>/dev/null; echo "$*" > "$STF" 2>/dev/null; echo "pomelo-ai-start: $*" >&2; exit 1; }

running_pid() {   # prints the pid when the recorded process is a live llama-server
    [ -r "$PIDF" ] || return 1
    p=$(head -n 1 "$PIDF" 2>/dev/null)
    case $p in ''|*[!0-9]*) return 1;; esac
    case $(cat /proc/$p/comm 2>/dev/null) in llama-server*) echo "$p"; return 0;; esac
    return 1
}

PORT=$(conf PORT 8080)
case $PORT in ''|*[!0-9]*) PORT=8080;; esac

do_stop() {
    p=$(running_pid) || { echo "pomelo-ai-start: not running"; return 0; }
    kill "$p" 2>/dev/null
    i=0; while [ $i -lt 50 ] && [ -d /proc/$p ]; do sleep 0.1 2>/dev/null || sleep 1; i=$((i+1)); done
    [ -d /proc/$p ] && kill -9 "$p" 2>/dev/null
    rm -f "$PIDF"
    echo "pomelo-ai-start: stopped"
}

do_start() {
    if p=$(running_pid); then echo "pomelo-ai-start: already running (pid $p, port $PORT)"; return 0; fi
    rm -f "$STF"
    SERVER=$(conf SERVER "" sys)
    if [ -z "$SERVER" ]; then
        for c in /usr/lib/pomelo/ai/llama-server /persist/ai/bin/llama-server /c/ProgramData/Pomelo/AI/bin/llama-server; do
            [ -x "$c" ] && { SERVER=$c; break; }
        done
    fi
    [ -x "$SERVER" ] || fail "找不到 llama-server（/usr/lib/pomelo/ai/llama-server）：這個映像沒有安裝 AI 服務的執行檔。"
    MODEL=$(conf MODEL "")
    if [ -z "$MODEL" ] || [ ! -f "$MODEL" ]; then
        MODEL=
        for d in $(conf MODEL_DIRS "/persist/ai/models /c/ProgramData/Pomelo/AI/models"); do
            for m in "$d"/*.gguf; do [ -f "$m" ] && { MODEL=$m; break 2; }; done
        done
    fi
    [ -n "$MODEL" ] || fail "找不到模型檔：請自己把 .gguf 模型放進 /persist/ai/models 或 C:\\ProgramData\\Pomelo\\AI\\models（映像不內建模型，也不會自動下載）。"
    THREADS=$(conf THREADS "")
    # default: all CPUs but one (the kernel does not honour nice/setpriority yet, so -t is the only way to leave CPU to the desktop)
    case $THREADS in ''|*[!0-9]*) THREADS=$(grep -c '^processor' /proc/cpuinfo 2>/dev/null); THREADS=$(( ${THREADS:-2} - 1 )); [ "$THREADS" -ge 1 ] || THREADS=1;; esac
    CTX=$(conf CTX 2048);       case $CTX in ''|*[!0-9]*) CTX=2048;; esac
    PAR=$(conf PARALLEL 4);     case $PAR in ''|*[!0-9]*) PAR=4;; esac
    EXTRA=$(conf EXTRA_ARGS "" sys)
    case $EXTRA in *--host*|*--port*|*-m\ *|*--model*) fail "EXTRA_ARGS 不能改 --host、--port、--model（服務一律只聽 127.0.0.1）。";; esac
    mkdir -p "$RT" "$CACHE" 2>/dev/null
    echo "== $(date 2>/dev/null) start $SERVER -m $MODEL" >> "$LOG" 2>/dev/null
    # CTX is shared by the parallel slots: llama-server divides --ctx-size by --parallel
    # shellcheck disable=SC2086
    "$SERVER" --host 127.0.0.1 --port "$PORT" -m "$MODEL" -t "$THREADS" -c $((CTX * PAR)) --parallel "$PAR" --no-webui $EXTRA </dev/null >> "$LOG" 2>&1 &
    echo $! > "$PIDF"
    sleep 1
    if ! running_pid >/dev/null; then
        rm -f "$PIDF"
        fail "AI 服務一啟動就結束了：$(tail -n 1 "$LOG" 2>/dev/null)（完整紀錄：$LOG）"
    fi
    echo "pomelo-ai-start: started (pid $(head -n 1 "$PIDF"), 127.0.0.1:$PORT, model $MODEL); loading..."
}

case ${1:-start} in
start) do_start;;
stop) do_stop;;
restart) do_stop; do_start;;
status)
    if p=$(running_pid); then echo "running pid $p port $PORT"; else echo "not running"; exit 3; fi;;
*) echo "usage: pomelo-ai-start [start|stop|restart|status]" >&2; exit 2;;
esac
