#!/bin/bash
# BTX Keeper — complete removal. Asks once, then removes everything.
set -u
KEEPER_HOME="$HOME/.btx-keeper"
PLIST="$HOME/Library/LaunchAgents/com.btx.keeper.plist"

echo "This removes the BTX Keeper completely: the launchd agent, the node,"
echo "and everything under $KEEPER_HOME (about $(du -sh "$KEEPER_HOME" 2>/dev/null | cut -f1 || echo '?'))."
printf "Type yes to continue: "
read -r answer
[ "$answer" = "yes" ] || { echo "left untouched."; exit 0; }

launchctl unload "$PLIST" 2>/dev/null || true
rm -f "$PLIST"
pkill -f "btx-keeper-run.sh" 2>/dev/null || true
pkill -f "btx-keeper-watchdog.sh" 2>/dev/null || true

if pgrep -f "^$KEEPER_HOME/bin/btxd" >/dev/null; then
    echo "stopping the node cleanly (can take a few minutes)…"
    "$KEEPER_HOME/bin/btx-cli" -datadir="$KEEPER_HOME" stop 2>/dev/null || true
    for _ in $(seq 1 60); do
        pgrep -f "^$KEEPER_HOME/bin/btxd" >/dev/null || break
        sleep 5
    done
fi

# NEVER rm -rf under a live btxd: deleting LevelDB dirs out from under it can
# crash it mid-write, and a node still flushing after 5 minutes is exactly a
# node mid-write. The agent and supervisors are already gone, so nothing will
# restart it — wait it out and run this again.
if pgrep -f "^$KEEPER_HOME/bin/btxd" >/dev/null; then
    echo "btxd is STILL flushing after 5 minutes — not deleting $KEEPER_HOME under a live node."
    echo "Give it a few more minutes (watch: pgrep -fl btxd), then run this uninstaller again."
    exit 1
fi

rm -rf "$KEEPER_HOME"
echo "BTX Keeper removed. Thank you for the uptime you gave the network."
