#!/bin/sh
# AETHER node — DSM start/stop/status hook. DSM calls this to run the node and
# keep it alive. The node reaches OUT only (no inbound ports), holds encrypted
# copies of beings, and never exceeds its size cap.
#
# v1.0.1+: uses the system / SynoCommunity python3 instead of a bundled one;
# the `cryptography` dep is pip-installed into the package's own var/pylib by
# postinst, so we don't pollute the host's site-packages.

PKG="aether-node"
TARGET="/var/packages/${PKG}/target"
VAR="/var/packages/${PKG}/var"
APP="${TARGET}/app/peer_client.py"
PYLIB="${VAR}/pylib"
CONF="${VAR}/config.env"
PIDFILE="${VAR}/node.pid"
LOG="${VAR}/node.log"

# Find a python3 the package can use. First match wins.
find_python() {
    for p in \
        /var/packages/py3k/target/usr/local/bin/python3 \
        /usr/local/bin/python3 \
        /usr/bin/python3 \
        /opt/bin/python3 \
        "${TARGET}/python/bin/python3" ; do
        if [ -x "$p" ]; then echo "$p"; return 0; fi
    done
    return 1
}

start_daemon() {
    [ -f "$CONF" ] && . "$CONF"
    SHARDS="${SHARDS_DIR:-$VAR/shards}"
    mkdir -p "$SHARDS"
    NODES="${NODES:-https://aether-us.ai-ministries.com,https://aether-uk.ai-ministries.com}"
    NODE_ID="${NODE_ID:-nas-$(hostname)}"
    MAP_LABEL="${MAP_LABEL:-NAS-NODE}"
    MAX_GB="${MAX_GB:-5}"
    PY="$(find_python)"
    if [ -z "$PY" ]; then
        echo "$(date) — no python3 found in any standard path" >>"$LOG"
        return 1
    fi
    export MESH_TOKEN
    export PYTHONPATH="${PYLIB}:${PYTHONPATH}"
    "$PY" "$APP" --nodes "$NODES" --id "$NODE_ID" --dir "$SHARDS" \
        --map-label "$MAP_LABEL" --map-kind storage --max-gb "$MAX_GB" >>"$LOG" 2>&1 &
    echo $! > "$PIDFILE"
}

stop_daemon() {
    [ -f "$PIDFILE" ] && kill "$(cat "$PIDFILE")" 2>/dev/null
    rm -f "$PIDFILE"
}

case "$1" in
    start)  start_daemon ;;
    stop)   stop_daemon ;;
    status)
        if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
            exit 0
        fi
        exit 1 ;;
    *) echo "usage: $0 {start|stop|status}"; exit 1 ;;
esac
exit 0
