Files
KlipperAnywhere/packaging/rinkhals/klipperanywhere-agent/app.sh
T
2026-05-14 02:27:26 +01:00

146 lines
3.2 KiB
Bash

#!/bin/sh
set -e
TOOLS_SH=/useremain/rinkhals/.current/tools.sh
wait_for_tools() {
tries=30
while [ "$tries" -gt 0 ]; do
if [ -f "$TOOLS_SH" ]; then
return 0
fi
tries=$((tries - 1))
sleep 2
done
return 1
}
if ! wait_for_tools; then
echo "missing Rinkhals tools.sh" >&2
exit 2
fi
. "$TOOLS_SH"
APP_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
APP_LOG="$APP_ROOT/klipperanywhere-agent.log"
APP_PID="$APP_ROOT/klipperanywhere-agent.pid"
APP_LOCK="$APP_ROOT/.start.lock"
AGENT_BIN="$APP_ROOT/klipperanywhere-agent"
AGENT_CFG="$APP_ROOT/agent.json"
agent_pids() {
PIDS=""
if [ -f "$APP_PID" ]; then
PID=$(cat "$APP_PID" 2>/dev/null || true)
if [ -n "$PID" ]; then
PIDS="$PID"
fi
fi
for proc in /proc/[0-9]*; do
[ -e "$proc/cmdline" ] || continue
pid=${proc#/proc/}
case " $PIDS " in
*" $pid "*) continue ;;
esac
cmd=$(tr '\0' ' ' < "$proc/cmdline" 2>/dev/null || true)
case "$cmd" in
*"$AGENT_BIN"*)
PIDS="$PIDS $pid"
;;
esac
done
echo "$PIDS"
}
status() {
PIDS=$(agent_pids)
if [ -n "$PIDS" ]; then
report_status "$APP_STATUS_STARTED" "$PIDS"
return
fi
rm -f "$APP_PID"
report_status "$APP_STATUS_STOPPED" ""
}
start() {
cd "$APP_ROOT"
if mkdir "$APP_LOCK" 2>/dev/null; then
echo "$$" > "$APP_LOCK/pid"
trap 'rm -rf "$APP_LOCK"' EXIT INT TERM
else
LOCK_PID=$(cat "$APP_LOCK/pid" 2>/dev/null || true)
if [ -n "$LOCK_PID" ] && kill -0 "$LOCK_PID" 2>/dev/null; then
sleep 2
PIDS=$(agent_pids)
if [ -n "$PIDS" ]; then
exit 0
fi
echo "another start is already in progress" >&2
exit 1
fi
rm -rf "$APP_LOCK"
mkdir "$APP_LOCK"
echo "$$" > "$APP_LOCK/pid"
trap 'rm -rf "$APP_LOCK"' EXIT INT TERM
fi
if [ ! -x "$AGENT_BIN" ]; then
echo "missing agent binary: $AGENT_BIN" >&2
exit 1
fi
if [ ! -f "$AGENT_CFG" ]; then
echo "missing agent config: $AGENT_CFG" >&2
exit 1
fi
PIDS=$(agent_pids)
if [ -n "$PIDS" ]; then
exit 0
fi
: > "$APP_LOG"
echo "starting KlipperAnywhere agent" >> "$APP_LOG"
PID=$(sh -c 'cd "$1" && nohup "$2" -config "$3" >> "$4" 2>&1 </dev/null & printf "%s\n" $!' sh "$APP_ROOT" "$AGENT_BIN" "$AGENT_CFG" "$APP_LOG" 2>/dev/null | tail -n1 | tr -d '\r')
if [ -z "$PID" ]; then
echo "failed to launch KlipperAnywhere agent" >&2
exit 1
fi
echo "$PID" > "$APP_PID"
sleep 2
if ! kill -0 "$PID" 2>/dev/null; then
echo "KlipperAnywhere agent exited immediately; see $APP_LOG" >&2
rm -f "$APP_PID"
exit 1
fi
}
stop() {
PIDS=$(agent_pids)
if [ -n "$PIDS" ]; then
for PID in $PIDS; do
kill "$PID" 2>/dev/null || true
done
sleep 2
REMAINING=""
for PID in $PIDS; do
if kill -0 "$PID" 2>/dev/null; then
REMAINING="$REMAINING $PID"
fi
done
if [ -n "$REMAINING" ]; then
for PID in $REMAINING; do
kill -KILL "$PID" 2>/dev/null || true
done
sleep 1
fi
fi
rm -f "$APP_PID"
rm -rf "$APP_LOCK"
}
case "${1:-}" in
status) status ;;
start) start ;;
stop) stop ;;
*)
echo "usage: $0 {status|start|stop}" >&2
exit 2
;;
esac