#!/bin/bash
#
# net-dns-monitor-service -- install and supervise the Net-DNS-Monitor menu bar app.
#
# Keeps the app running: launchd restarts it immediately if it crashes or is
# killed, and starts it at login. Supervision is gated on a flag file so there
# is still a way to turn the app off deliberately (see "The Quit problem").
#
#   net-dns-monitor-service install     # copy bundle, write LaunchAgent, start
#   net-dns-monitor-service status      # is it running, is it ticking
#   net-dns-monitor-service stop        # deliberately off, stays off
#   net-dns-monitor-service start       # back on, supervised
#   net-dns-monitor-service restart
#   net-dns-monitor-service check       # one-shot "restart it if it died"
#   net-dns-monitor-service update      # re-copy a freshly built bundle
#   net-dns-monitor-service logs [-f]
#   net-dns-monitor-service uninstall
#
# ---------------------------------------------------------------------------
# Why launchd owns the process, and nothing else may start it
#
# All start/stop/restart goes through launchctl. Launching the bundle any other
# way -- `open -n Net-DNS-Monitor.app`, or a scripts/start.sh run from before
# this agent was installed (start.sh refuses to launch while it is loaded) --
# creates a process launchd does not track. `launchctl list` then shows no PID,
# this script concludes the app is down, launches its own copy, and the user
# gets two menu bar icons. `status` and `check` therefore also look for
# untracked copies and warn about them.
#
# The Quit problem
#
# The app's original LaunchAgent deliberately had no KeepAlive, with a good
# reason recorded in it: with KeepAlive, choosing Quit in the menu bar just
# relaunches the app, so there would be no way to turn it off. Keeping the app
# always running and keeping Quit meaningful are genuinely in tension.
#
# This resolves it with launchd's KeepAlive/PathState: the app is supervised
# only while the flag file below exists. So Quit is indeed overridden -- the
# app comes straight back, which is what "always running" was asked for -- but
# `stop` removes the flag and the app then stays down until `start`. The off
# switch moved from the menu bar to this script rather than disappearing.
# ---------------------------------------------------------------------------

set -euo pipefail

# Every path below, including the rm -rf in replace_installed_bundle, is built
# from $HOME. Empty, it would resolve to /Applications and /Library.
[ -n "${HOME:-}" ] || { printf 'error: HOME is not set\n' >&2; exit 1; }

LABEL="com.mitchhudson.net-dns-monitor"
SERVICE="gui/$(id -u)/$LABEL"

SUPPORT_DIR="$HOME/Library/Application Support/net-dns-monitor"
FLAG="$SUPPORT_DIR/supervise.enabled"
KEEPALIVE_LOG="$SUPPORT_DIR/keepalive.log"
RESOLUTION_LOG="$SUPPORT_DIR/resolution-log.jsonl"
REPORTS_DIR="$SUPPORT_DIR/reports"

INSTALLED_APP="$HOME/Applications/Net-DNS-Monitor.app"
EXEC="$INSTALLED_APP/Contents/MacOS/Net-DNS-Monitor"
EXEC_NAME="Net-DNS-Monitor"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
APP_LOG="$HOME/Library/Logs/net-dns-monitor.launchd.log"

# launchd refuses to respawn a job that stopped less than this many seconds ago.
#
# One constant, used both in the generated plist below AND by the waits in
# `start`/`restart`/`check`. They used to be unrelated: the plist said 15 and the
# restart path read the pid immediately after killing the app, so a completely
# normal restart reported `running: no` -- launchd was simply not allowed to start
# it again yet. `update` inherited that, which made a successful update look like
# it had killed the app for good.
THROTTLE_SECONDS=15

# How long past the throttle window to keep waiting before calling it a failure.
RESPAWN_GRACE_SECONDS=10

# The py2app build output the bundle is installed *from*. It usually lives in a
# checkout's dist/, and a checkout (a worktree especially) can be removed at any
# time -- which is exactly why `install` copies the bundle out to ~/Applications
# instead of pointing launchd straight at it. Only `install` and `update` read
# this path, and both fail with a clear message if it is gone.
#
# Resolved in this order:
#   1. NDM_SOURCE_BUNDLE, when set.
#   2. The path the last successful install or update copied from, recorded in
#      $SOURCE_BUNDLE_RECORD, while that directory still exists. scripts/install.sh
#      copies this script to ~/.local/bin, where the script's own location says
#      nothing about where the build is: without the record, `update` there looked
#      for ~/.local/dist and died, and `install` kept the old bundle.
#   3. The dist/ build of the checkout this script lives in.
SOURCE_BUNDLE_RECORD="$SUPPORT_DIR/source-bundle"
SCRIPT_REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." 2>/dev/null && pwd)"
if [ -n "${NDM_SOURCE_BUNDLE:-}" ]; then
    SOURCE_BUNDLE="$NDM_SOURCE_BUNDLE"
    SOURCE_BUNDLE_ORIGIN="NDM_SOURCE_BUNDLE"
elif [ -s "$SOURCE_BUNDLE_RECORD" ] && [ -d "$(head -n 1 "$SOURCE_BUNDLE_RECORD")" ]; then
    SOURCE_BUNDLE="$(head -n 1 "$SOURCE_BUNDLE_RECORD")"
    SOURCE_BUNDLE_ORIGIN="recorded by the last install/update in $SOURCE_BUNDLE_RECORD"
else
    SOURCE_BUNDLE="$SCRIPT_REPO/dist/Net-DNS-Monitor.app"
    SOURCE_BUNDLE_ORIGIN="the checkout this script is in"
fi

say()  { printf '%s\n' "$*"; }
warn() { printf '%s\n' "$*" >&2; }
die()  { printf 'error: %s\n' "$*" >&2; exit 1; }

# Mutating commands share one reservation through rollback and launchd reload.
# A stale reservation fails closed; an operator can inspect it before removal.
acquire_service_lock() {
    mkdir -p "$SUPPORT_DIR"
    SERVICE_LOCK="$SUPPORT_DIR/service-install.lock"
    mkdir "$SERVICE_LOCK" 2>/dev/null || die "another service command owns $SERVICE_LOCK"
    trap 'rmdir "$SERVICE_LOCK"' EXIT
}

xml_escape() {
    printf '%s' "$1" | sed -e 's/\&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g' -e 's/"/\&quot;/g' -e "s/'/\&apos;/g"
}

# Append to the keepalive log. `check` runs unattended from a timer, so its
# decisions have to leave a trace somewhere durable.
audit() {
    mkdir -p "$SUPPORT_DIR"
    printf '%s %s\n' "$(date '+%Y-%m-%dT%H:%M:%S%z')" "$*" >>"$KEEPALIVE_LOG"
}

# --- state inspection ------------------------------------------------------

# PID of the launchd-managed app, or nothing. launchd is the only authority
# here. `launchctl print` against $SERVICE, the same domain is_loaded and every
# kickstart use, shows a "pid = N" line only while the job runs. `launchctl list
# <label>` was the other source, which left two functions querying different views.
#
# Deliberately not `pgrep -f netdnsmonitor`: -f scans whole command lines, so
# any unrelated process that merely mentions the app (an editor, a grep, an
# agent invocation quoting this path) matches, and the check silently becomes a
# no-op that always believes the app is up. That false positive was observed
# for real while writing this.
running_pid() {
    local out
    out=$(launchctl print "$SERVICE" 2>/dev/null) || return 0
    printf '%s\n' "$out" | awk '$1 == "pid" && $2 == "=" { gsub(/[^0-9]/, "", $3); print $3; exit }'
}

# Exact-name match, so this cannot suffer the argv false positive above.
# Used only to detect copies launchd does not own.
all_app_pids() { pgrep -x "$EXEC_NAME" 2>/dev/null || true; }

untracked_pids() {
    local tracked; tracked="$(running_pid)"
    local pid
    for pid in $(all_app_pids); do
        [ "$pid" = "$tracked" ] || printf '%s\n' "$pid"
    done
}

is_loaded()     { launchctl print "$SERVICE" >/dev/null 2>&1; }
is_supervised() { [ -e "$FLAG" ]; }

# Poll for a running pid for up to $1 seconds; print it and succeed if one
# appears, print nothing and fail if the window elapses.
#
# Every caller that kickstarts the job needs this. `launchctl kickstart` returns
# as soon as launchd has *accepted* the request, not when a process exists, and
# after a kill launchd will sit on that request for ThrottleInterval seconds. Any
# code that reads running_pid on the next line is therefore asking a question
# launchd cannot answer yet, and printing "running: no" for the answer.
wait_for_pid() {
    local limit="${1:-0}" deadline pid
    deadline=$(( $(date +%s) + limit ))
    while :; do
        pid="$(running_pid)"
        if [ -n "$pid" ]; then
            printf '%s\n' "$pid"
            return 0
        fi
        [ "$(date +%s)" -ge "$deadline" ] && return 1
        sleep 1
    done
}

# --- LaunchAgent -----------------------------------------------------------

write_plist() {
    mkdir -p "$(dirname "$PLIST")"
    # Written beside the target and linted before the move, so a failed lint
    # leaves the working plist alone instead of replacing it with a broken one.
    local staged exec_xml flag_xml log_xml
    staged="$(mktemp "$PLIST.XXXXXX")"
    exec_xml="$(xml_escape "$EXEC")"
    flag_xml="$(xml_escape "$FLAG")"
    log_xml="$(xml_escape "$APP_LOG")"
    cat >"$staged" <<PLIST_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>$LABEL</string>

	<!-- Generated by net-dns-monitor-service. Edit that script, not this file;
	     \`install\` overwrites this plist. -->

	<!-- A LaunchAgent, not a LaunchDaemon, on purpose: this is a rumps menu bar
	     app and needs the logged-in user's GUI session. A daemon runs before
	     login with no window server access and could never draw a status item.

	     ProgramArguments points at the executable *inside* the .app bundle
	     rather than at \`python -m netdnsmonitor.app\`. That matters: framework
	     Python re-execs itself into its own bundled Python.app the instant
	     rumps creates the GUI, so a bare module launch shows "Python" in the
	     Dock / Force Quit / Cmd-Tab. The py2app-frozen bundle embeds a private
	     interpreter that never takes that path.

	     The path is ~/Applications, NOT the dist/ directory inside the git
	     worktree the bundle was built in. Anything under .claude/worktrees/ can
	     be removed at any time, and when it is, login startup breaks silently. -->
	<key>ProgramArguments</key>
	<array>
		<string>$exec_xml</string>
	</array>

	<!-- Deliberately NO RunAtLoad. It would start the app whenever this agent
	     is loaded, which includes every login, regardless of the flag file
	     below. Verified on macOS 26.4: with the flag removed, a bootstrap with
	     RunAtLoad set started the app anyway, so \`stop\` would silently undo
	     itself at the next login. KeepAlive alone is enough to start the job at
	     load when its condition holds, so login startup still works, and it
	     works for the correct reason: because supervision is enabled. -->

	<!-- Restart the app whenever it stops, for any reason, as long as the flag
	     file exists. Removing the flag (\`net-dns-monitor-service stop\`) tells
	     launchd to stop supervising and shut the app down; recreating it
	     (\`start\`) brings it back. This is the deliberate off switch that
	     replaces the menu bar Quit item, which KeepAlive necessarily overrides. -->
	<key>KeepAlive</key>
	<dict>
		<key>PathState</key>
		<dict>
			<key>$flag_xml</key>
			<true/>
		</dict>
	</dict>

	<!-- Don't respawn faster than this if the app is crash-looping. The value
	     comes from \$THROTTLE_SECONDS in this script so that the restart/start
	     waits know how long launchd is entitled to take; hard-coding it here was
	     what made a throttled respawn look like a dead app. -->
	<key>ThrottleInterval</key>
	<integer>$THROTTLE_SECONDS</integer>

	<!-- launchd starts processes with no LANG/LC_* at all, which makes the
	     frozen app's locale encoding US-ASCII. That is what caused incident
	     reports to be written as 0-byte .md files: an unencoded open() raised
	     UnicodeEncodeError on the first curly quote. report_storage now pins
	     encoding="utf-8" explicitly, so this is belt-and-braces rather than
	     the fix; a UTF-8 locale is nonetheless what the app would get from a
	     normal shell, and matching that removes a class of surprise. -->
	<key>EnvironmentVariables</key>
	<dict>
		<key>LANG</key>
		<string>en_US.UTF-8</string>
	</dict>

	<key>ProcessType</key>
	<string>Interactive</string>

	<key>StandardOutPath</key>
	<string>$log_xml</string>
	<key>StandardErrorPath</key>
	<string>$log_xml</string>
</dict>
</plist>
PLIST_EOF
    if ! plutil -lint "$staged" >/dev/null; then
        rm -f "$staged"
        die "generated plist is malformed; $PLIST was not changed"
    fi
    mv -f "$staged" "$PLIST"
}

# A successful bootstrap is required to apply the rewritten plist.
reload_agent() {
    if ! launchctl bootout "$SERVICE" 2>/dev/null; then
        is_loaded && die "could not remove the loaded $LABEL; replacement was not loaded"
    fi
    local attempt
    for attempt in 1 2 3; do
        if launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null; then
            return 0
        fi
        sleep 1
    done
    die "could not bootstrap $LABEL (try: launchctl bootstrap gui/$(id -u) '$PLIST')"
}

# Replace the installed bundle with $SOURCE_BUNDLE as a whole-bundle swap.
#
# Not `ditto "$SOURCE_BUNDLE" "$INSTALLED_APP"` onto the existing bundle: ditto
# merges into a destination that exists (checked: a file present only in the
# destination survives the copy). A file the new build no longer contains -- a
# deleted or renamed module, a dropped dependency -- stays behind in the
# installed copy, where the frozen app can still import it, and where it is not
# covered by the bundle's signature. Copying into a sibling first and swapping
# also means a copy that fails part way leaves the installed bundle untouched
# rather than half old and half new.
#
# ditto rather than cp -R for the copy itself: it preserves the bundle's
# resource forks, symlinks and ad-hoc code signature, which cp -R can invalidate.
replace_installed_bundle() {
    local staged="$INSTALLED_APP.new" previous="$INSTALLED_APP.old"
    local source_real staged_real previous_real installed_real
    source_real="$(cd "$SOURCE_BUNDLE" && pwd -P)" || die "cannot resolve source bundle"
    staged_real="$(cd "$(dirname "$staged")" && pwd -P)/$(basename "$staged")"
    previous_real="$(cd "$(dirname "$previous")" && pwd -P)/$(basename "$previous")"
    # Resolve existing swap directories too, including symlink aliases.
    if [ -d "$staged" ]; then staged_real="$(cd "$staged" && pwd -P)"; fi
    if [ -d "$previous" ]; then previous_real="$(cd "$previous" && pwd -P)"; fi
    case "$source_real/" in
        "$staged_real/"*|"$previous_real/"*) die "source bundle overlaps a reserved swap directory" ;;
    esac
    installed_real="$(cd "$(dirname "$INSTALLED_APP")" && pwd -P)/$(basename "$INSTALLED_APP")"
    if [ -d "$INSTALLED_APP" ]; then installed_real="$(cd "$INSTALLED_APP" && pwd -P)"; fi
    case "$staged_real/" in "$source_real/"*) die "source bundle contains a reserved swap directory" ;; esac
    case "$previous_real/" in "$source_real/"*) die "source bundle contains a reserved swap directory" ;; esac
    if [ "$source_real" != "$installed_real" ]; then
        case "$source_real/" in "$installed_real/"*) die "source bundle is inside the installed bundle" ;; esac
    fi
    rm -rf "$staged" "$previous"
    if ! ditto "$SOURCE_BUNDLE" "$staged"; then
        rm -rf "$staged"
        die "copying $SOURCE_BUNDLE failed; $INSTALLED_APP was not changed"
    fi
    if [ ! -x "$staged/Contents/MacOS/$EXEC_NAME" ]; then
        rm -rf "$staged"
        die "$SOURCE_BUNDLE has no executable at Contents/MacOS/$EXEC_NAME; $INSTALLED_APP was not changed"
    fi
    if [ -e "$INSTALLED_APP" ]; then
        mv "$INSTALLED_APP" "$previous" \
            || die "could not move the old bundle aside; $INSTALLED_APP was not changed (new copy left at $staged)"
    fi
    if ! mv "$staged" "$INSTALLED_APP"; then
        # Put the old bundle back so launchd still has something to run.
        if [ -e "$previous" ]; then
            mv "$previous" "$INSTALLED_APP" || true
        fi
        die "could not move the new bundle into place at $INSTALLED_APP"
    fi
    rm -rf "$previous"
}

# Remember where the bundle just installed came from, as an absolute path, so
# a later `update` from a copy of this script outside any checkout finds it.
record_source_bundle() {
    mkdir -p "$SUPPORT_DIR"
    printf '%s\n' "$(cd "$SOURCE_BUNDLE" && pwd)" > "$SOURCE_BUNDLE_RECORD"
}

# --- commands --------------------------------------------------------------

check_no_standalone_login_agent() {
    local legacy="com.netdnsmonitor"
    local legacy_target="gui/$(id -u)/$legacy"
    if [ -e "$HOME/Library/LaunchAgents/$legacy.plist" ] ||
        launchctl print "$legacy_target" >/dev/null 2>&1; then
        die "the standalone Start at Login agent is still enabled.
  Turn off Start at Login in the menu bar. If the old agent is loaded,
  log out and back in before retrying the supervised install."
    fi
}

cmd_install() {
    check_no_standalone_login_agent
    mkdir -p "$SUPPORT_DIR" "$HOME/Applications" "$(dirname "$APP_LOG")"

    if [ -d "$SOURCE_BUNDLE" ]; then
        say "Installing bundle from build output ($SOURCE_BUNDLE_ORIGIN):"
        say "  $SOURCE_BUNDLE"
        say "  -> $INSTALLED_APP"
        replace_installed_bundle
        record_source_bundle
    elif [ -n "${NDM_SOURCE_BUNDLE:-}" ]; then
        # An explicit path that does not exist is a typo or a deleted build, and
        # silently keeping the old bundle would report success for the wrong thing.
        die "NDM_SOURCE_BUNDLE is set but is not a directory: $NDM_SOURCE_BUNDLE"
    elif [ -x "$EXEC" ]; then
        warn "note: build output not found at $SOURCE_BUNDLE ($SOURCE_BUNDLE_ORIGIN)"
        warn "      keeping the already-installed bundle at $INSTALLED_APP"
    else
        die "no bundle to install. Build it first, from the checkout you want to run:
    ./scripts/start.sh      # builds dist/Net-DNS-Monitor.app
  then re-run: NDM_SOURCE_BUNDLE=\"\$PWD/dist/Net-DNS-Monitor.app\" $0 install"
    fi

    [ -x "$EXEC" ] || die "installed bundle has no executable at $EXEC"

    write_plist
    touch "$FLAG"
    audit "install: supervising $EXEC"
    reload_agent          # KeepAlive starts the app; no separate launch needed

    # A fresh bootstrap is not throttled, but the process still takes a moment to
    # exist, and status read immediately after would report "no".
    wait_for_pid "$RESPAWN_GRACE_SECONDS" >/dev/null || true

    say ""
    cmd_status
}

cmd_start() {
    [ -f "$PLIST" ] || die "not installed yet -- run: $0 install"
    touch "$FLAG"
    is_loaded || reload_agent
    if [ -z "$(running_pid)" ]; then
        launchctl kickstart "$SERVICE" 2>/dev/null || true
        # A job stopped moments ago is still inside its throttle window, so this
        # waits rather than letting cmd_status report a "no" that only means
        # "not yet".
        wait_for_pid $(( THROTTLE_SECONDS + RESPAWN_GRACE_SECONDS )) >/dev/null || true
    fi
    audit "start: supervision enabled"
    cmd_status
}

cmd_stop() {
    # Remove the flag FIRST. While it exists, KeepAlive would just restart
    # whatever we kill.
    rm -f "$FLAG"
    launchctl kill SIGTERM "$SERVICE" 2>/dev/null || true
    # SIGTERM is a request. Wait for the process to go so the report below is
    # about what happened, not about what was asked.
    local waited=0
    while [ -n "$(running_pid)" ] && [ "$waited" -lt 10 ]; do
        sleep 1
        waited=$(( waited + 1 ))
    done
    if [ -n "$(running_pid)" ]; then
        audit "stop: supervision disabled but pid $(running_pid) still running after ${waited}s"
        warn "Supervision disabled, but the app (pid $(running_pid)) is still running after ${waited}s."
        warn "It will not be restarted when it exits. To end it now: kill $(running_pid)"
    else
        audit "stop: supervision disabled by request"
        say "Supervision disabled. The app will stay stopped, including across"
        say "login, until: $0 start"
    fi
    say ""
    cmd_status
}

cmd_restart() {
    [ -f "$PLIST" ] || die "not installed yet -- run: $0 install"
    touch "$FLAG"
    is_loaded || reload_agent

    # -k kills the running instance; KeepAlive brings it back, but not for up to
    # ThrottleInterval seconds. The old version reported status on the very next
    # line and so announced `running: no` for every successful restart -- and
    # `update` calls this, which made a good update look like it had killed the
    # app permanently.
    launchctl kickstart -k "$SERVICE" 2>/dev/null || launchctl kickstart "$SERVICE" 2>/dev/null || true

    local wait_seconds=$(( THROTTLE_SECONDS + RESPAWN_GRACE_SECONDS )) pid
    say "waiting up to ${wait_seconds}s for launchd to respawn it (ThrottleInterval is ${THROTTLE_SECONDS}s)..."
    pid="$(wait_for_pid "$wait_seconds")" || pid=""

    if [ -z "$pid" ]; then
        # Past the throttle window with nothing running. Ask for it directly
        # instead of waiting on KeepAlive, then allow one more short window.
        launchctl kickstart "$SERVICE" 2>/dev/null || true
        pid="$(wait_for_pid "$RESPAWN_GRACE_SECONDS")" || pid=""
    fi

    if [ -n "$pid" ]; then
        audit "restart: running as pid $pid"
    else
        audit "restart: no pid after $(( wait_seconds + RESPAWN_GRACE_SECONDS ))s"
        warn "restart requested but nothing is running yet -- check $APP_LOG"
    fi
    say ""
    cmd_status
}

# One-shot supervision check. KeepAlive already does this continuously; this
# exists for a manual "is it up, fix it if not", and as the fallback if
# KeepAlive/PathState is ever unavailable. To run it on a timer instead, add a
# second LaunchAgent with StartInterval and ProgramArguments = [this script,
# "check"] -- but then drop KeepAlive from the app's plist, because two
# supervisors fighting over one process is its own failure mode.
cmd_check() {
    if ! is_supervised; then
        audit "check: skipped, supervision disabled (no flag file)"
        say "supervision disabled -- not starting. Enable with: $0 start"
        return 0
    fi
    [ -f "$PLIST" ] || die "not installed yet -- run: $0 install"

    if ! is_loaded; then
        audit "check: agent was not loaded, bootstrapping"
        reload_agent
        say "restarted: LaunchAgent was not loaded"
        return 0
    fi

    local pid; pid="$(running_pid)"
    if [ -n "$pid" ]; then
        say "ok: running (pid $pid)"
        return 0
    fi

    audit "check: app was not running, kickstarting"
    launchctl kickstart "$SERVICE" 2>/dev/null || true
    # Waits, for the same reason restart does: reading the pid on the next line
    # asks launchd a question it cannot answer until the throttle window is up,
    # and this function exists specifically to answer "is it up".
    pid="$(wait_for_pid $(( THROTTLE_SECONDS + RESPAWN_GRACE_SECONDS )))" || pid=""
    if [ -n "$pid" ]; then
        say "restarted: app was not running (now pid $pid)"
    else
        audit "check: kickstart did not yield a running pid"
        warn "restart attempted but no pid yet -- see $APP_LOG"
    fi
}

cmd_update() {
    [ -d "$SOURCE_BUNDLE" ] || die "build output not found: $SOURCE_BUNDLE ($SOURCE_BUNDLE_ORIGIN)
  Nothing to update from. If the checkout it was built in was removed, rebuild
  the bundle and set NDM_SOURCE_BUNDLE to the new one; a successful update
  records that path for next time."
    say "Updating $INSTALLED_APP from $SOURCE_BUNDLE ($SOURCE_BUNDLE_ORIGIN)"
    replace_installed_bundle
    record_source_bundle
    audit "update: re-copied bundle from $SOURCE_BUNDLE"
    # cmd_restart re-creates the flag, which would undo a deliberate `stop`.
    if is_supervised; then
        cmd_restart
    else
        say "Bundle replaced. Supervision is off (stopped on purpose), so the app was not started; '$0 start' runs the new build."
        say ""
        cmd_status
    fi
}

# Age of a file in whole seconds, or nothing if it doesn't exist.
file_age_seconds() {
    [ -e "$1" ] || return 0
    local mtime now
    mtime=$(stat -f %m "$1") || return 0
    now=$(date +%s)
    printf '%s\n' "$(( now - mtime ))"
}

# Seconds the given pid has been alive, or nothing. The wedged-process check
# below needs this: a stale resolution log right after a start means only that
# the app was down until a moment ago, not that the new process is stuck.
#
# BSD ps has no `etimes` (seconds) keyword -- that is a Linux/procps extension,
# and asking for it on macOS makes ps dump its whole keyword list instead. So
# parse `etime`, whose format is [[dd-]hh:]mm:ss.
process_uptime_seconds() {
    [ -n "${1:-}" ] || return 0
    local etime rest days=0 h=0 m=0 s=0
    etime=$(ps -o etime= -p "$1" 2>/dev/null | tr -d ' ') || return 0
    [ -n "$etime" ] || return 0

    rest="$etime"
    case "$rest" in *-*) days="${rest%%-*}"; rest="${rest#*-}" ;; esac

    local IFS=:
    # shellcheck disable=SC2086  # deliberate word splitting on IFS
    set -- $rest
    if [ "$#" -eq 3 ]; then h="$1"; m="$2"; s="$3"
    elif [ "$#" -eq 2 ]; then m="$1"; s="$2"
    else return 0
    fi

    # 10# forces base 10 so a zero-padded field like 08 isn't read as octal.
    printf '%s\n' "$(( 10#$days * 86400 + 10#$h * 3600 + 10#$m * 60 + 10#$s ))"
}

cmd_status() {
    local pid age reports
    pid="$(running_pid)"

    say "net-dns-monitor"
    if [ ! -f "$PLIST" ]; then
        say "  supervised   : not installed -- run: $0 install"
    elif is_supervised; then
        say "  supervised   : yes (flag present)"
    else
        say "  supervised   : NO -- stopped on purpose; '$0 start' to resume"
    fi
    say "  agent loaded : $(is_loaded && echo yes || echo no)"
    if [ -n "$pid" ]; then
        say "  running      : yes (pid $pid)"
    else
        say "  running      : no"
    fi
    say "  bundle       : $EXEC"
    if [ -f "$PLIST" ]; then
        local program
        program=$(plutil -extract ProgramArguments.0 raw -o - "$PLIST" 2>/dev/null || echo "?")
        say "  agent runs   : $program"
        [ "$program" = "$EXEC" ] || warn "  WARNING: the LaunchAgent points somewhere else -- re-run '$0 install'"
    else
        say "  agent plist  : (missing -- not installed)"
    fi

    # Liveness that actually means something. A PID only proves the process is
    # resident; the resolution log is appended every resolution_interval_seconds
    # (default 300), so a recent mtime proves the app is still ticking.
    age="$(file_age_seconds "$RESOLUTION_LOG")"
    if [ -n "$age" ]; then
        say "  last tick    : resolution log written ${age}s ago"
        # Only meaningful once this process has been up longer than the write
        # interval it is being judged against. Straight after a start the log
        # is stale because the app was down, which says nothing about the new
        # process.
        local uptime; uptime="$(process_uptime_seconds "$pid")"
        if [ -n "$pid" ] && [ -n "$uptime" ] && [ "$uptime" -gt 900 ] && [ "$age" -gt 900 ]; then
            warn "  WARNING: up for ${uptime}s but hasn't written in ${age}s -- it may be wedged."
            warn "           KeepAlive only restarts a process that exits, never one that hangs."
            warn "           Force a clean restart with: $0 restart"
        elif [ -n "$pid" ] && [ -n "$uptime" ] && [ "$uptime" -lt 900 ]; then
            say "  uptime       : ${uptime}s (too new to judge whether it is ticking)"
        fi
    else
        say "  last tick    : no resolution log yet"
    fi

    if [ -d "$REPORTS_DIR" ]; then
        reports=$(find "$REPORTS_DIR" -name '*.json' -type f | wc -l | tr -d ' ')
        say "  incidents    : $reports report(s) in $REPORTS_DIR"
    fi

    local dupes; dupes="$(untracked_pids | tr '\n' ' ' | sed 's/ $//')"
    if [ -n "$dupes" ]; then
        warn "  WARNING: copies running that launchd does not manage (pid(s): $dupes)."
        warn "           Two menu bar icons come from this -- usually scripts/start.sh"
        warn "           or 'open -n' was used. Clean up with: kill $dupes"
    fi

    if [ -f "$APP_LOG" ] && [ -s "$APP_LOG" ]; then
        # The age matters: this log is append-only and never rotated, so an old
        # traceback sits at the tail forever and reads as if it just happened.
        local log_age; log_age="$(file_age_seconds "$APP_LOG")"
        say ""
        say "  last app log lines (written ${log_age:-?}s ago, $APP_LOG):"
        tail -n 3 "$APP_LOG" | sed 's/^/    /'
    fi
}

cmd_logs() {
    say "--- app log: $APP_LOG"
    if [ "${1:-}" = "-f" ]; then
        touch "$APP_LOG"
        tail -f "$APP_LOG"
    else
        [ -f "$APP_LOG" ] && tail -n 40 "$APP_LOG" || say "(empty)"
        say ""
        say "--- supervision log: $KEEPALIVE_LOG"
        [ -f "$KEEPALIVE_LOG" ] && tail -n 20 "$KEEPALIVE_LOG" || say "(empty)"
    fi
}

cmd_uninstall() {
    rm -f "$FLAG"
    launchctl bootout "$SERVICE" 2>/dev/null || true
    if is_loaded; then
        audit "uninstall: bootout did not unload the agent"
        die "the agent is still loaded after bootout; the plist was left in place. Try: launchctl bootout $SERVICE"
    fi
    rm -f "$PLIST"
    audit "uninstall: agent removed"
    say "Removed the LaunchAgent and disabled supervision."
    say "Left in place: $INSTALLED_APP, and everything under"
    say "  $SUPPORT_DIR"
    say "Delete those by hand if you want them gone."
}

usage() {
    sed -n '3,28p' "$0" | sed 's/^# \{0,1\}//'
    exit "${1:-0}"
}

case "${1:-status}" in
    install|update|start|stop|restart|check|uninstall) acquire_service_lock ;;
esac

case "${1:-status}" in
    install)   cmd_install ;;
    start)     cmd_start ;;
    stop)      cmd_stop ;;
    restart)   cmd_restart ;;
    check)     cmd_check ;;
    update)    cmd_update ;;
    status)    cmd_status ;;
    logs)      shift; cmd_logs "${1:-}" ;;
    uninstall) cmd_uninstall ;;
    -h|--help|help) usage 0 ;;
    *) warn "unknown command: $1"; usage 1 ;;
esac
