#!/usr/bin/env bash
set -euo pipefail

# Interface level of this script (not the agent version). 2: --auth-secret-stdin,
# --auth-secret-file, --version, --dry-run. Tractus AI checks it before asking
# for the secret, so an older copy never gets one.
INSTALL_SCRIPT_VERSION=2
# Fixes within a level (same flags, same install/v<level>/ path). r2: restart
# an agent that is already running instead of leaving the old process. r3:
# --dry-run shows the secret as ****. r4: a reinstall or migration keeps the
# existing config's other settings (dns_servers, ap_ssid, …) and updates an
# installed WiFi Helper too. r5: optional --docker-log-rotation (no change to
# the secret flags Tractus AI checks the level for). r6: the agent's unit sets
# LimitCORE=0 (no core file may hold the model key or a decrypted model).
# r7: OOMScoreAdjust=-900, so memory pressure never takes down the agent that recovers the station.
# r8: a reinstall drops an unfinished server_url_update trial (server_url_previous, server_url_trial).
# r9: downloads try a list of addresses (Frankfurt, then Oregon); --base-url or
# TRACTUS_UPDATE_BASE forces one.
# r10 (D10f T12): runs as `curl … | sudo bash`: the body is one function called on
# the last line (a half-downloaded script runs nothing), no secret source asks on
# the terminal without echo, and --server-url defaults to the production address.
# Every level-2 command line works as before, so the level stays 2.
INSTALL_SCRIPT_REVISION=10

BINARY="tractus-ai-agent"
# Tractus AI production (settings.public.agentUrl); test and on-prem pass --server-url.
DEFAULT_SERVER_URL="wss://agent.tractus.ai/agent"
UNINSTALL_SCRIPT="tractus-ai-agent-uninstall"
# Download addresses in order; the binary and the uninstall script come from
# the same one. The agent's own updater uses the same list (updater.rs).
DOWNLOAD_BASES=(
    "https://tractus-ai-agent-eu.s3.eu-central-1.amazonaws.com"
    "https://tractus-ai.s3.us-west-2.amazonaws.com"
)
CONFIG_DIR="/etc/tractus-ai-agent"
SERVICE_NAME="tractus-ai-agent"
WIFI_SERVICE_NAME="tractus-ai-wifi-helper"
DOCKER_DAEMON_JSON="/etc/docker/daemon.json"

# The whole body runs from main, called on the last line: piped through
# `curl | sudo bash`, a download cut short defines nothing and runs nothing.
main() {

# ── CLI parsing ───────────────────────────────────────────────────────────────

SERVER_URL=""
AUTH_SECRET=""
AUTH_SECRET_SOURCES=0
AUTH_SECRET_ARG=false
DRY_RUN=false
CHANNEL="stable"
DNS_SERVERS=""
START_SERVICE=true
INSTALL_WIFI_HELPER=false
WIFI_AP_SSID=""
DOCKER_LOG_ROTATION=""
BASE_URL="${TRACTUS_UPDATE_BASE:-}"

usage() {
    cat <<EOF
Usage: $(basename "$0") [--server-url <URL>] [--auth-secret-stdin | --auth-secret-file <FILE>] [OPTIONS]

  Without a secret option the node secret is asked on the terminal (not echoed).

OPTIONS:
  --server-url <URL>           Tractus AI server WebSocket URL
                               (default: $DEFAULT_SERVER_URL)
  --auth-secret-stdin          Read the node secret from standard input (not with
                               \`curl … | bash\`: there stdin is the script)
  --auth-secret-file <FILE>    Read the node secret from FILE; it must not be
                               readable by group or others (e.g. mode 0600)
  --auth-secret <SECRET>       Deprecated: the secret ends up in shell history and
                               sudo logs. Still accepted, with a warning.
  --channel <stable|nightly>   Update channel (default: stable)
  --dns-servers <ip1,ip2,...>  Comma-separated DNS servers (default: system DNS)
  --no-start                   Install and register service without starting it
  --wifi-helper                Also register the tractus-ai-wifi-helper service
                               (captive portal for offline WiFi reconfiguration)
  --wifi-helper-ap-ssid <SSID> AP network name (requires --wifi-helper;
                               default: Tractus-WiFi-Setup)
  --docker-log-rotation <SIZE>,<FILES>
                               Linux: limit every container's log in
                               $DOCKER_DAEMON_JSON (log-opts max-size and
                               max-file, e.g. 50m,5). Applies after Docker
                               restarts, to containers created from then on;
                               the script does not restart Docker
  --base-url <URL>             Download only from this address (https; default: the
                               built-in list, Frankfurt then Oregon). Also from
                               the TRACTUS_UPDATE_BASE environment variable. The
                               agent's own updates use update_urls in config.toml
  --dry-run                    Check the options and print the config that would be
                               written (including the secret), install nothing
  --version                    Print the script's interface level and exit
  -h, --help                   Show this help

EXAMPLES:
  curl -fsSL https://get.tractus.ai | sudo bash
  curl -fsSL https://get.tractus.ai | sudo bash -s -- --server-url wss://test.tractus.ai/agent
  read -rsp "Node secret: " S; echo
  printf '%s' "\$S" | sudo bash $(basename "$0") --server-url wss://tractus.example.com/agent --auth-secret-stdin; unset S
  sudo bash $(basename "$0") --server-url wss://tractus.example.com/agent --auth-secret-file /root/node-secret --wifi-helper
  sudo bash $(basename "$0") --server-url wss://tractus.example.com/agent --auth-secret-file /root/node-secret --dns-servers 8.8.8.8,8.8.4.4
EOF
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --server-url)    SERVER_URL="$2";           shift 2 ;;
        --server-url=*)  SERVER_URL="${1#*=}";      shift   ;;
        --auth-secret)   AUTH_SECRET="$2"; AUTH_SECRET_ARG=true; AUTH_SECRET_SOURCES=$((AUTH_SECRET_SOURCES+1)); shift 2 ;;
        --auth-secret=*) AUTH_SECRET="${1#*=}"; AUTH_SECRET_ARG=true; AUTH_SECRET_SOURCES=$((AUTH_SECRET_SOURCES+1)); shift ;;
        --auth-secret-stdin)
            # Piped (`curl … | bash`), stdin is the script itself; there
            # BASH_SOURCE names no file ("" on bash 3, "main" on bash 5).
            [[ -f "${BASH_SOURCE[0]:-}" ]] || {
                echo "error: --auth-secret-stdin cannot be used with \`curl … | bash\` (stdin is the script); leave it out to be asked on the terminal, or use --auth-secret-file" >&2; exit 1; }
            AUTH_SECRET="$(cat)"; AUTH_SECRET_SOURCES=$((AUTH_SECRET_SOURCES+1)); shift ;;
        --auth-secret-file|--auth-secret-file=*)
            if [[ "$1" == *=* ]]; then f="${1#*=}"; shift; else f="${2:-}"; shift 2 || shift; fi
            [[ -f "$f" ]] || { echo "error: --auth-secret-file: not a regular file: $f" >&2; exit 1; }
            perm="$(stat -c %a "$f" 2>/dev/null || stat -f %Lp "$f")"
            (( (8#$perm & 8#077) == 0 )) || {
                echo "error: --auth-secret-file: $f is readable by group or others (mode $perm); use chmod 600" >&2; exit 1; }
            AUTH_SECRET="$(cat "$f")"; AUTH_SECRET_SOURCES=$((AUTH_SECRET_SOURCES+1)) ;;
        --dry-run)       DRY_RUN=true;              shift   ;;
        --version)       echo "$(basename "$0") $INSTALL_SCRIPT_VERSION r$INSTALL_SCRIPT_REVISION"; exit 0 ;;
        --channel)       CHANNEL="$2";              shift 2 ;;
        --channel=*)     CHANNEL="${1#*=}";         shift   ;;
        --dns-servers)   DNS_SERVERS="$2";          shift 2 ;;
        --dns-servers=*) DNS_SERVERS="${1#*=}";     shift   ;;
        --no-start)             START_SERVICE=false;       shift   ;;
        --wifi-helper)          INSTALL_WIFI_HELPER=true;  shift   ;;
        --wifi-helper-ap-ssid)  WIFI_AP_SSID="$2";         shift 2 ;;
        --wifi-helper-ap-ssid=*) WIFI_AP_SSID="${1#*=}";   shift   ;;
        --docker-log-rotation)   DOCKER_LOG_ROTATION="$2";  shift 2 ;;
        --docker-log-rotation=*) DOCKER_LOG_ROTATION="${1#*=}"; shift ;;
        --base-url)             BASE_URL="$2";             shift 2 ;;
        --base-url=*)           BASE_URL="${1#*=}";        shift   ;;
        -h|--help)              usage; exit 0 ;;
        *) echo "error: unknown option: $1" >&2; echo ""; usage >&2; exit 1 ;;
    esac
done

[[ -z "$SERVER_URL" ]] && SERVER_URL="$DEFAULT_SERVER_URL"
(( AUTH_SECRET_SOURCES <= 1 )) || { echo "error: give the secret only once (--auth-secret-stdin, --auth-secret-file or --auth-secret)" >&2; exit 1; }
# No secret option: ask on the terminal, not echoed (also under `curl | sudo bash`,
# where stdin is the script). Without a terminal (automation) stop, never install
# without a secret.
if (( AUTH_SECRET_SOURCES == 0 )); then
    if ( exec </dev/tty ) 2>/dev/null; then
        IFS= read -rsp "Node secret: " AUTH_SECRET </dev/tty || true
        echo >&2
    else
        echo "error: no node secret given and no terminal to ask on; use --auth-secret-file <FILE> (or --auth-secret-stdin when the script is a file)" >&2
        exit 1
    fi
fi
[[ -z "$AUTH_SECRET" ]] && { echo "error: a node secret is required (asked on the terminal, or --auth-secret-file / --auth-secret-stdin)" >&2; echo ""; usage >&2; exit 1; }
[[ "$AUTH_SECRET" =~ [[:cntrl:]] ]] && { echo "error: the node secret contains control characters" >&2; exit 1; }
if [[ -n "$BASE_URL" ]]; then
    BASE_URL="${BASE_URL%/}"
    [[ "$BASE_URL" =~ ^https://[^/@?#[:space:]]+(/[^?#[:space:]]*)?$ ]] || {
        echo "error: --base-url must be an https:// address without user info, query or spaces" >&2; exit 1; }
    DOWNLOAD_BASES=("$BASE_URL")
fi
$AUTH_SECRET_ARG && echo "warning: --auth-secret puts the secret in shell history and sudo logs; use --auth-secret-stdin or --auth-secret-file" >&2

# TOML basic string: escape backslash and double quote (control characters are rejected above).
toml_str() {
    local v="$1"
    v="${v//\\/\\\\}"
    v="${v//\"/\\\"}"
    printf '"%s"' "$v"
}
[[ "$CHANNEL" != "stable" && "$CHANNEL" != "nightly" ]] && {
    echo "error: --channel must be 'stable' or 'nightly'" >&2; exit 1; }
[[ -n "$WIFI_AP_SSID" && "$INSTALL_WIFI_HELPER" != "true" ]] && {
    echo "error: --wifi-helper-ap-ssid requires --wifi-helper" >&2; exit 1; }
LOG_MAX_SIZE=""
LOG_MAX_FILE=""
if [[ -n "$DOCKER_LOG_ROTATION" ]]; then
    [[ "$DOCKER_LOG_ROTATION" =~ ^([1-9][0-9]*[kmg]),([1-9][0-9]?)$ ]] || {
        echo "error: --docker-log-rotation must be <SIZE>,<FILES>, e.g. 50m,5 (size in k/m/g, 1-99 files)" >&2; exit 1; }
    LOG_MAX_SIZE="${BASH_REMATCH[1]}"
    LOG_MAX_FILE="${BASH_REMATCH[2]}"
fi

# daemon.json with log-opts max-size/max-file set, every other key kept.
# Reads the current file (may be empty) on stdin; needs python3.
merged_daemon_json() {
    python3 -c '
import json, sys
size, files = sys.argv[1], sys.argv[2]
raw = sys.stdin.read().strip()
try:
    d = json.loads(raw) if raw else {}
except ValueError as e:
    sys.exit(f"error: daemon.json is not valid JSON ({e}); fix it or set log-opts by hand")
if not isinstance(d, dict):
    sys.exit("error: daemon.json is not a JSON object")
driver = d.get("log-driver", "json-file")
if driver not in ("json-file", "local"):
    sys.exit(f"error: daemon.json uses log-driver {driver}; max-size/max-file apply only to json-file and local")
opts = d.get("log-opts") or {}
opts["max-size"], opts["max-file"] = size, files
d["log-opts"] = opts
print(json.dumps(d, indent=2))
' "$1" "$2"
}

# ── Config ────────────────────────────────────────────────────────────────────

# Insecure URL (http:// or ws://) → tls_skip_verify.
TLS_INSECURE=false
if [[ "$SERVER_URL" == http://* || "$SERVER_URL" == ws://* ]]; then
    TLS_INSECURE=true
fi

# dns_servers TOML array if provided.
DNS_LINE=""
if [[ -n "$DNS_SERVERS" ]]; then
    dns_toml="["
    first=true
    IFS=',' read -ra DNS_ARRAY <<< "$DNS_SERVERS"
    for ip in "${DNS_ARRAY[@]}"; do
        ip="$(echo "$ip" | tr -d ' ')"
        [[ -z "$ip" ]] && continue
        $first || dns_toml+=", "
        dns_toml+="$(toml_str "$ip")"
        first=false
    done
    dns_toml+="]"
    DNS_LINE="dns_servers = $dns_toml"
fi

# The existing config.toml (reinstall, migration): every setting this script
# does not write itself is kept, so a migration never drops an operator's
# dns_servers, ap_ssid or tuning. Read as root where needed.
EXISTING_CONFIG=""
read_existing_config() {
    local f="$CONFIG_DIR/config.toml"
    if [[ -r "$f" ]]; then
        EXISTING_CONFIG="$(cat "$f")"
    elif [[ -e "$f" ]] && command -v sudo &>/dev/null && sudo -n true 2>/dev/null; then
        EXISTING_CONFIG="$(sudo cat "$f")"
    fi
    return 0
}

# Lines of the existing config ($1) to keep: top-level keys this script does
# not set (a multi-line array value stays whole) and every table after them.
# $2 = "masked": password/secret/token values shown as **** (dry run).
preserved_config() {
    # server_url_previous / server_url_trial: a server_url_update trial in
    # progress (agent >= 0.9.2); the given --server-url ends it.
    local managed=" server_url auth_secret channel tls_skip_verify server_url_previous server_url_trial "
    [[ -n "$DNS_LINE" ]] && managed+="dns_servers "
    [[ -n "$WIFI_AP_SSID" ]] && managed+="ap_ssid "
    printf '%s\n' "$1" | awk -v managed="$managed" -v masked="${2:-}" '
        /^[[:space:]]*\[/ && !cont { in_table = 1 }
        {
            if (cont) {
                if (keep) print
                if ($0 ~ /\]/) cont = 0
                next
            }
            if (match($0, /^[[:space:]]*[A-Za-z0-9_-]+[[:space:]]*=/)) {
                key = $0; sub(/^[[:space:]]*/, "", key); sub(/[[:space:]]*=.*/, "", key)
                value = $0; sub(/^[^=]*=[[:space:]]*/, "", value)
                keep = in_table || !index(managed, " " key " ")
                if (value ~ /^\[/ && value !~ /\]/) cont = 1
                if (!keep) next
                if (masked == "masked" && tolower(key) ~ /(password|secret|token)/) {
                    sub(/=.*/, "= \"****\"")
                }
                print
                next
            }
            if (in_table) print
        }'
}

# $1 = "masked": print the secret as **** (dry run; the output may be logged).
build_config() {
    echo "server_url  = $(toml_str "$SERVER_URL")"
    if [[ "${1:-}" == "masked" ]]; then
        echo "# auth_secret: hidden in --dry-run (${#AUTH_SECRET} characters)"
        echo 'auth_secret = "****"'
    else
        echo "auth_secret = $(toml_str "$AUTH_SECRET")"
    fi
    echo "channel     = $(toml_str "$CHANNEL")"
    [[ -n "$DNS_LINE" ]]     && echo "$DNS_LINE"
    $TLS_INSECURE            && echo "tls_skip_verify = true"
    [[ -n "$WIFI_AP_SSID" ]] && echo "ap_ssid = $(toml_str "$WIFI_AP_SSID")"
    [[ -n "$EXISTING_CONFIG" ]] && preserved_config "$EXISTING_CONFIG" "${1:-}"
    return 0
}

if $DRY_RUN; then
    read_existing_config
    build_config masked
    echo ""
    printf '# download from: %s\n' "${DOWNLOAD_BASES[@]}"
    if [[ -n "$DOCKER_LOG_ROTATION" ]]; then
        echo ""
        echo "# $DOCKER_DAEMON_JSON would become:"
        { cat "$DOCKER_DAEMON_JSON" 2>/dev/null || true; } | merged_daemon_json "$LOG_MAX_SIZE" "$LOG_MAX_FILE"
    fi
    exit 0
fi

# ── Platform detection ────────────────────────────────────────────────────────

OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
    Linux)
        case "$ARCH" in
            x86_64)        TARGET="x86_64-unknown-linux-gnu" ;;
            aarch64|arm64) TARGET="aarch64-unknown-linux-gnu" ;;
            armv7*|armv6*) TARGET="armv7-unknown-linux-gnueabihf" ;;
            *) echo "error: unsupported architecture: $ARCH" >&2; exit 1 ;;
        esac
        ;;
    Darwin)
        case "$ARCH" in
            x86_64) TARGET="x86_64-apple-darwin" ;;
            arm64)  TARGET="aarch64-apple-darwin" ;;
            *) echo "error: unsupported architecture: $ARCH" >&2; exit 1 ;;
        esac
        ;;
    *)
        echo "error: unsupported OS: $OS" >&2
        exit 1
        ;;
esac

# ── Privilege helpers ─────────────────────────────────────────────────────────

# run_inst: used for INSTALL_DIR (may or may not need sudo)
if [[ "$EUID" -eq 0 ]]; then
    INSTALL_DIR="/usr/local/bin"
    run_inst() { "$@"; }
    priv()     { "$@"; }
elif [[ -w /usr/local/bin ]]; then
    INSTALL_DIR="/usr/local/bin"
    run_inst() { "$@"; }
    priv()     { sudo "$@"; }
elif command -v sudo &>/dev/null && sudo -n true 2>/dev/null; then
    INSTALL_DIR="/usr/local/bin"
    run_inst() { sudo "$@"; }
    priv()     { sudo "$@"; }
else
    INSTALL_DIR="$HOME/.local/bin"
    mkdir -p "$INSTALL_DIR"
    run_inst() { "$@"; }
    priv() {
        echo "error: root or sudo is required to write to system directories" >&2
        exit 1
    }
fi

# ── Download helper ───────────────────────────────────────────────────────────

if ! command -v curl &>/dev/null && ! command -v wget &>/dev/null; then
    echo "error: neither curl nor wget found" >&2
    exit 1
fi

download() {
    local url="$1" dest="$2"
    if command -v curl &>/dev/null; then
        curl -fsSL --connect-timeout 20 "$url" -o "$dest"
    else
        wget -q -T 20 -O "$dest" "$url"
    fi
}

# ── Download binary & uninstall script ───────────────────────────────────────

echo "Detected : $OS / $ARCH → $TARGET"
echo "Installing to : $INSTALL_DIR"
echo ""

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

FETCHED=""
for base in "${DOWNLOAD_BASES[@]}"; do
    echo "Downloading $BINARY ($CHANNEL) from $base..."
    if download "$base/agent/$CHANNEL/latest/$TARGET/$BINARY" "$TMP_DIR/$BINARY" \
        && download "$base/$UNINSTALL_SCRIPT.sh" "$TMP_DIR/$UNINSTALL_SCRIPT"; then
        FETCHED="$base"
        break
    fi
    echo "  not available there, trying the next address" >&2
    rm -f "$TMP_DIR/$BINARY" "$TMP_DIR/$UNINSTALL_SCRIPT"
done
[[ -n "$FETCHED" ]] || { echo "error: could not download $BINARY from: ${DOWNLOAD_BASES[*]}" >&2; exit 1; }
chmod +x "$TMP_DIR/$BINARY"
sed -i.bak "s|__INSTALL_DIR__|$INSTALL_DIR|g" "$TMP_DIR/$UNINSTALL_SCRIPT"
rm -f "$TMP_DIR/$UNINSTALL_SCRIPT.bak"
chmod +x "$TMP_DIR/$UNINSTALL_SCRIPT"

run_inst mv "$TMP_DIR/$BINARY"           "$INSTALL_DIR/$BINARY"
run_inst mv "$TMP_DIR/$UNINSTALL_SCRIPT" "$INSTALL_DIR/$UNINSTALL_SCRIPT"

echo "✓ $INSTALL_DIR/$BINARY"
echo "✓ $INSTALL_DIR/$UNINSTALL_SCRIPT"

# ── Write config.toml ─────────────────────────────────────────────────────────

echo ""
echo "Writing $CONFIG_DIR/config.toml..."
if [[ -f "$CONFIG_DIR/config.toml" ]]; then
    EXISTING_CONFIG="$(priv cat "$CONFIG_DIR/config.toml")"
    echo "  keeping the existing config's other settings"
fi

priv mkdir -p "$CONFIG_DIR"

CONFIG_TMP="$(mktemp)"
build_config > "$CONFIG_TMP"

priv cp "$CONFIG_TMP" "$CONFIG_DIR/config.toml"
rm -f "$CONFIG_TMP"
priv chmod 640 "$CONFIG_DIR/config.toml"

echo "✓ $CONFIG_DIR/config.toml"

if $TLS_INSECURE; then
    echo ""
    echo "⚠  WARNING: server-url uses an insecure protocol ($SERVER_URL)."
    echo "   tls_skip_verify = true has been added to config.toml."
    echo "   Do NOT use this in production — switch to wss:// or https://."
fi

# ── Docker log rotation (optional) ───────────────────────────────────────────

if [[ -n "$DOCKER_LOG_ROTATION" ]]; then
    echo ""
    if [[ "$OS" != "Linux" ]]; then
        echo "⚠  --docker-log-rotation is ignored on $OS (Docker Desktop: Settings → Docker Engine)."
    elif ! command -v python3 &>/dev/null; then
        echo "error: --docker-log-rotation needs python3 to edit $DOCKER_DAEMON_JSON" >&2; exit 1
    else
        current="$(priv cat "$DOCKER_DAEMON_JSON" 2>/dev/null || true)"
        merged="$(printf '%s' "$current" | merged_daemon_json "$LOG_MAX_SIZE" "$LOG_MAX_FILE")"
        if [[ -n "$current" ]] && [[ "$(printf '%s' "$current" | python3 -c 'import json,sys; print(json.dumps(json.load(sys.stdin), indent=2))')" == "$merged" ]]; then
            echo "Docker log rotation already set (max-size $LOG_MAX_SIZE, max-file $LOG_MAX_FILE)."
        else
            priv mkdir -p "$(dirname "$DOCKER_DAEMON_JSON")"
            if [[ -n "$current" ]] && ! priv test -e "$DOCKER_DAEMON_JSON.bak-tractus"; then
                priv cp -p "$DOCKER_DAEMON_JSON" "$DOCKER_DAEMON_JSON.bak-tractus"
            fi
            printf '%s\n' "$merged" | priv tee "$DOCKER_DAEMON_JSON.tmp-tractus" >/dev/null
            priv mv "$DOCKER_DAEMON_JSON.tmp-tractus" "$DOCKER_DAEMON_JSON"
            echo "Docker log rotation written to $DOCKER_DAEMON_JSON (max-size $LOG_MAX_SIZE, max-file $LOG_MAX_FILE)."
            echo "   It applies after Docker restarts (sudo systemctl restart docker), which"
            echo "   restarts running containers: do it at a quiet moment. Containers keep"
            echo "   their old log settings until they are recreated."
        fi
    fi
fi

# ── Register & start service ──────────────────────────────────────────────────

echo ""
echo "Registering service..."

# An installed WiFi Helper runs the same binary: update and restart it too,
# even without --wifi-helper (a reinstall or migration must not leave it on
# the old binary). Its own settings stay in the kept config.
if [[ "$OS" == "Linux" && "$INSTALL_WIFI_HELPER" != "true" && -f "/etc/systemd/system/$WIFI_SERVICE_NAME.service" ]]; then
    echo "  WiFi Helper is installed: updating it too"
    INSTALL_WIFI_HELPER=true
fi

if [[ "$OS" == "Linux" ]]; then
    if ! command -v systemctl &>/dev/null; then
        echo "⚠  systemd not found — skipping service registration"
    else
        # ── Main agent service ────────────────────────────────────────────────
        priv tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
[Unit]
Description=Tractus AI Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=$INSTALL_DIR/$BINARY
Restart=always
LimitCORE=0
OOMScoreAdjust=-900
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
        priv systemctl daemon-reload
        priv systemctl enable "$SERVICE_NAME"
        echo "✓ systemd service registered and enabled"

        if $START_SERVICE; then
            # restart, not start: on a device that already runs the agent
            # (reinstall, migration) start is a no-op and the old process
            # would keep the old binary and config.
            priv systemctl restart "$SERVICE_NAME"
            echo "✓ service started"
            echo ""
            echo "  Status : systemctl status $SERVICE_NAME"
            echo "  Logs   : journalctl -u $SERVICE_NAME -f"
        else
            echo "  Start manually : systemctl start $SERVICE_NAME"
        fi

        # ── WiFi Helper service (optional) ────────────────────────────────────
        if $INSTALL_WIFI_HELPER; then
            echo ""
            echo "Registering WiFi Helper service..."

            priv tee /etc/systemd/system/$WIFI_SERVICE_NAME.service > /dev/null <<EOF
[Unit]
Description=Tractus AI WiFi Helper
# Start after network is up, but does not require internet
After=network.target
Wants=network.target

[Service]
Type=simple
ExecStart=$INSTALL_DIR/$BINARY --mode wifi-helper
Restart=always
RestartSec=10
# Tear down any open AP on stop
ExecStop=/bin/sh -c 'nmcli con delete tractus-wifi-helper 2>/dev/null || true'

[Install]
WantedBy=multi-user.target
EOF
            priv systemctl daemon-reload
            priv systemctl enable "$WIFI_SERVICE_NAME"
            echo "✓ WiFi Helper systemd service registered and enabled"

            if $START_SERVICE; then
                priv systemctl restart "$WIFI_SERVICE_NAME"
                echo "✓ WiFi Helper service started"
                echo ""
                echo "  Status : systemctl status $WIFI_SERVICE_NAME"
                echo "  Logs   : journalctl -u $WIFI_SERVICE_NAME -f"
            else
                echo "  Start manually : systemctl start $WIFI_SERVICE_NAME"
            fi
        fi
    fi

elif [[ "$OS" == "Darwin" ]]; then
    PLIST="/Library/LaunchDaemons/com.tractus.ai.agent.plist"
    # A loaded job keeps running the old binary and config: unload it first.
    [[ -f "$PLIST" ]] && { priv launchctl unload "$PLIST" 2>/dev/null || true; }
    priv tee "$PLIST" > /dev/null <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.tractus.ai.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>$INSTALL_DIR/$BINARY</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/var/log/tractus-ai-agent.log</string>
    <key>StandardErrorPath</key>
    <string>/var/log/tractus-ai-agent.log</string>
</dict>
</plist>
EOF
    priv launchctl load -w "$PLIST"
    echo "✓ launchd service registered"

    if $START_SERVICE; then
        priv launchctl start com.tractus.ai.agent
        echo "✓ service started"
        echo ""
        echo "  Logs : tail -f /var/log/tractus-ai-agent.log"
    else
        echo "  Start manually : launchctl start com.tractus.ai.agent"
    fi

    if $INSTALL_WIFI_HELPER; then
        echo ""
        echo "⚠  WiFi Helper (--wifi-helper) is only supported on Linux/systemd."
        echo "   Skipping WiFi Helper service registration on macOS."
    fi
fi

# ── PATH check ────────────────────────────────────────────────────────────────

if ! echo ":$PATH:" | grep -q ":$INSTALL_DIR:"; then
    echo ""
    echo "⚠  $INSTALL_DIR is not in your PATH. Add it:"
    if [[ -n "${ZSH_VERSION:-}" ]]; then
        echo "   echo 'export PATH=\"$INSTALL_DIR:\$PATH\"' >> ~/.zshrc && source ~/.zshrc"
    else
        echo "   echo 'export PATH=\"$INSTALL_DIR:\$PATH\"' >> ~/.bashrc && source ~/.bashrc"
    fi
fi

echo ""
echo "Installation complete."
echo "Run '$UNINSTALL_SCRIPT' to remove."

}

main "$@"
