cf/client/ddns-runner.sh

79 lines
2.1 KiB
Bash

#!/system/bin/sh
# Foreground wrapper that daemonizes ddns-report.sh.
#
# Usage:
# /data/local/tmp/ddns-runner.sh start # start in background (nohup)
# /data/local/tmp/ddns-runner.sh stop # stop the running instance
# /data/local/tmp/ddns-runner.sh status # print pid + last log lines
# /data/local/tmp/ddns-runner.sh restart
#
# The main script path and pid file can be overridden via env vars.
SCRIPT="${DDNS_SCRIPT:-/data/local/tmp/ddns-report.sh}"
PIDFILE="${DDNS_PIDFILE:-/data/local/tmp/ddns.pid}"
LOG_FILE="${DDNS_LOG_FILE:-/data/local/tmp/ddns.log}"
is_running() {
[ -f "$PIDFILE" ] || return 1
pid=$(cat "$PIDFILE" 2>/dev/null)
[ -n "$pid" ] || return 1
# kill -0 tests existence without signaling.
kill -0 "$pid" 2>/dev/null
}
cmd_start() {
if is_running; then
echo "already running (pid=$(cat "$PIDFILE"))"
return 0
fi
if [ ! -x "$SCRIPT" ]; then
echo "script not executable: $SCRIPT" >&2
return 127
fi
# nohup detaches from the shell; setsid would be cleaner but toybox does
# not guarantee it on every Android build.
nohup "$SCRIPT" >/dev/null 2>&1 &
pid=$!
echo "$pid" >"$PIDFILE"
echo "started pid=$pid"
}
cmd_stop() {
if ! is_running; then
echo "not running"
rm -f "$PIDFILE"
return 0
fi
pid=$(cat "$PIDFILE")
kill "$pid" 2>/dev/null
# Wait up to 5s, then SIGKILL.
i=0
while kill -0 "$pid" 2>/dev/null && [ $i -lt 5 ]; do
sleep 1
i=$((i + 1))
done
kill -0 "$pid" 2>/dev/null && kill -9 "$pid" 2>/dev/null
rm -f "$PIDFILE"
echo "stopped pid=$pid"
}
cmd_status() {
if is_running; then
echo "running pid=$(cat "$PIDFILE")"
else
echo "stopped"
fi
if [ -f "$LOG_FILE" ]; then
echo "--- last 10 log lines ---"
/system/bin/toybox tail -n 10 "$LOG_FILE"
fi
}
case "${1:-}" in
start) cmd_start ;;
stop) cmd_stop ;;
restart) cmd_stop; cmd_start ;;
status) cmd_status ;;
*) echo "usage: $0 {start|stop|restart|status}" >&2; exit 2 ;;
esac