#!/usr/bin/env bash
# Copyright 2024-2026 The DragonX Developers
# Released under GPLv3
#
# Stops lightwalletd and its monitor process.

set -euo pipefail

PIDFILE="/tmp/lwd-monitor.pid"

# Stop the monitor first (if running), which will also stop lightwalletd
if [[ -f "$PIDFILE" ]]; then
    MON_PID=$(cat "$PIDFILE")
    if kill -0 "$MON_PID" 2>/dev/null; then
        echo "Stopping monitor (PID $MON_PID)..."
        kill "$MON_PID"
        # Wait briefly for cleanup
        for i in $(seq 1 10); do
            kill -0 "$MON_PID" 2>/dev/null || break
            sleep 0.5
        done
        echo "Monitor stopped."
    else
        echo "Stale monitor pidfile found, removing."
        rm -f "$PIDFILE"
    fi
fi

# Kill any remaining lightwalletd processes
LWDPIDS=$(pgrep -f 'lightwalletd.*-conf-file' 2>/dev/null || true)
if [[ -n "$LWDPIDS" ]]; then
    echo "Stopping lightwalletd (PID $LWDPIDS)..."
    kill $LWDPIDS 2>/dev/null || true
    sleep 1
    # Force kill if still running
    for pid in $LWDPIDS; do
        if kill -0 "$pid" 2>/dev/null; then
            echo "Force killing PID $pid..."
            kill -9 "$pid" 2>/dev/null || true
        fi
    done
    echo "lightwalletd stopped."
else
    echo "No lightwalletd process found."
fi
