#!/usr/bin/env bash
# run-long — long-running command handler (feature T14)
# Start a long-running command in the background, stream its output, and
# poll/wait on it without blocking the caller.
#
# Usage:
#   run-long start CMD... [--name NAME] [--log PATH]
#   run-long list
#   run-long status NAME
#   run-long tail NAME [-n N]
#   run-long attach NAME
#   run-long wait NAME [--timeout SECS]
#   run-long stop NAME [--signal SIG]
#   run-long clean NAME
#   run-long --help
#
# Jobs are stored under: ${RUNLONG_DIR:-$HOME/.local/share/sysadmin_agent/runlong}
set -uo pipefail

RUNLONG_DIR="${RUNLONG_DIR:-$HOME/.local/share/sysadmin_agent/runlong}"

usage() { awk 'NR>1 && /^#/{sub(/^# ?/,""); print} NR>1 && !/^#/ && NF{exit}' "$0"; }

require_job() {
    local id="${1:-}"
    [ -n "$id" ] || { echo "run-long: NAME is required" >&2; usage; exit 2; }
    [ -f "$RUNLONG_DIR/$id.pid" ] || { echo "run-long: no such job: $id" >&2; exit 1; }
}

job_log() { jq -r '.log // empty' "$RUNLONG_DIR/${1}.json" 2>/dev/null; }

start_job() {
    local name="" log="" cmd="" parts=()
    while [ $# -gt 0 ]; do
        case "$1" in
            --name) name="$2"; shift 2 ;;
            --log)  log="$2"; shift 2 ;;
            --)     shift; parts+=("$@"); break ;;
            -*)     echo "run-long: unknown option: $1" >&2; usage; exit 2 ;;
            *)      parts+=("$1"); shift ;;
        esac
    done
    cmd="${parts[*]}"
    [ -n "$cmd" ] || { echo "run-long: CMD is required" >&2; usage; exit 2; }
    mkdir -p "$RUNLONG_DIR"

    local base
    base="${name:-$(printf '%s' "$cmd" | tr -cs 'A-Za-z0-9._-' '_' | sed -e 's/^_*//' -e 's/_*$//' | cut -c1-32)}"
    base="${base:-job}"
    local id="$base" n=1
    while [ -e "$RUNLONG_DIR/$id.pid" ]; do n=$((n+1)); id="$base-$n"; done

    local pidf="$RUNLONG_DIR/$id.pid"
    local exitf="$RUNLONG_DIR/$id.exit"
    local logf="${log:-$RUNLONG_DIR/$id.log}"
    local metaf="$RUNLONG_DIR/$id.json"

    mkdir -p "$(dirname "$logf")"
    : > "$logf"
    rm -f "$exitf"

    # Outer shell runs the real command in a child shell, captures its exit
    # code to the .exit file, and detaches from the controlling terminal.
    setsid bash -c '
        bash -c "$1"
        rc=$?
        printf "%s\n" "$rc" > "$2"
    ' _ "$cmd" "$exitf" >>"$logf" 2>&1 &
    local pid=$!

    echo "$pid" > "$pidf"
    jq -n --arg id "$id" --arg name "$name" --arg cmd "$cmd" \
        --arg started "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg log "$logf" \
        '{id:$id, name:$name, cmd:$cmd, started_at:$started, log:$log, status:"running"}' \
        > "$metaf"

    echo "run-long: started '$id' (pid $pid)"
    echo "  log:      $logf"
    echo "  stream:   run-long attach $id"
    echo "  wait:     run-long wait $id"
    echo "  status:   run-long status $id"
}

list_jobs() {
    [ -d "$RUNLONG_DIR" ] || { echo "(no jobs)"; exit 0; }
    local f id pid exitf st started
    for f in "$RUNLONG_DIR"/*.pid; do
        [ -e "$f" ] || continue
        id="$(basename "$f" .pid)"
        pid="$(cat "$f")"
        exitf="$RUNLONG_DIR/$id.exit"
        if [ -f "$exitf" ]; then st="done (exit $(cat "$exitf"))";
        elif kill -0 "$pid" 2>/dev/null; then st="running";
        else st="unknown"; fi
        started="$(jq -r '.started_at // "?"' "$RUNLONG_DIR/$id.json" 2>/dev/null)"
        printf '%-32s %-18s %s  %s\n' "$id" "$st" "$pid" "$started"
    done
}

status_job() {
    local id="${1:-}"; require_job "$id"
    local pid exitf rc st
    pid="$(cat "$RUNLONG_DIR/$id.pid")"
    exitf="$RUNLONG_DIR/$id.exit"
    if [ -f "$exitf" ]; then rc="$(cat "$exitf")"; st="finished";
    elif kill -0 "$pid" 2>/dev/null; then rc=""; st="running";
    else rc=""; st="exited-no-code"; fi
    jq -n --arg id "$id" --arg pid "$pid" --arg st "$st" --arg rc "$rc" \
        --arg log "$(job_log "$id")" \
        '{id:$id, pid:$pid, status:$st, exit_code:$rc, log:$log}'
}

tail_job() {
    local id="${1:-}"; require_job "$id"
    local n=20
    [ "${2:-}" = "-n" ] && n="${3:-20}"
    tail -n "$n" "$(job_log "$id")"
}

attach_job() {
    local id="${1:-}"; require_job "$id"
    tail -n 40 -f "$(job_log "$id")"
}

wait_job() {
    local id="${1:-}"; require_job "$id"
    local timeout=0
    [ "${2:-}" = "--timeout" ] && timeout="${3:-0}"
    local exitf="$RUNLONG_DIR/$id.exit" waited=0
    while [ ! -f "$exitf" ]; do
        sleep 1; waited=$((waited+1))
        if [ "$timeout" -gt 0 ] && [ "$waited" -ge "$timeout" ]; then
            echo "run-long: job $id still running after ${timeout}s" >&2
            exit 1
        fi
    done
    local rc; rc="$(cat "$exitf")"
    echo "run-long: job $id finished with exit code $rc"
    exit "$rc"
}

stop_job() {
    local id="${1:-}"; require_job "$id"
    local sig="${2:-TERM}"
    local pid; pid="$(cat "$RUNLONG_DIR/$id.pid")"
    if kill -0 "$pid" 2>/dev/null; then
        # The job runs under setsid => its own process group; signal the whole
        # group so children/pipelines are not orphaned.
        kill -s "$sig" -- -"$pid" && echo "run-long: sent $sig to job $id (pgid $pid)"
    else
        echo "run-long: job $id is not running" >&2; exit 1
    fi
}

clean_job() {
    local id="${1:-}"; require_job "$id"
    rm -f "$RUNLONG_DIR/$id.pid" "$RUNLONG_DIR/$id.exit" "$RUNLONG_DIR/$id.json" "$RUNLONG_DIR/$id.log"
    echo "run-long: cleaned job $id"
}

case "${1:-}" in
    start)   shift; start_job "$@" ;;
    list)    list_jobs ;;
    status)  shift; status_job "$@" ;;
    tail)    shift; tail_job "$@" ;;
    attach)  shift; attach_job "$@" ;;
    wait)    shift; wait_job "$@" ;;
    stop)    shift; stop_job "$@" ;;
    clean)   shift; clean_job "$@" ;;
    --help|-h) usage ;;
    *) usage; exit 2 ;;
esac
