#!/bin/sh
# Close Continuity: stop the app and the record index, then lock the vault (ADR-006 §1).
#
#   tools/stop
#
# The index lives in RAM only; stopping it wipes that copy. After this, everything is
# encrypted again.
. "$(dirname "$0")/lib.sh"
tools=$(cd "$(dirname "$0")" && pwd)

if [ -n "$CONTINUITY_REMOTE" ]; then
    ssh "$CONTINUITY_REMOTE" 'sudo -n systemctl stop continuity.service' \
        || say "could not stop the app on $CONTINUITY_REMOTE; locking anyway"
else
    run=${XDG_RUNTIME_DIR:-$CONTINUITY_DATA}/continuity
    if [ -f "$run/app.pid" ]; then
        pid=$(cat "$run/app.pid")
        kill "$pid" 2>/dev/null || true
        i=0
        while kill -0 "$pid" 2>/dev/null && [ $i -lt 30 ]; do i=$((i + 1)); sleep 1; done
        kill -9 "$pid" 2>/dev/null || true
        rm -f "$run/app.pid"
    fi
    engine=${CONTINUITY_CONTAINER:-$(command -v podman || command -v docker || true)}
    if [ -n "$engine" ]; then "$engine" rm -f continuity-index >/dev/null 2>&1 || true; fi
fi

"$tools/lock"
say "stopped and locked"
