#!/bin/bash
#
# Stop all 5 local peers gracefully
#

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${CYAN}╔═══════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║         Stopping 5-Peer Network                  ║${NC}"
echo -e "${CYAN}╚═══════════════════════════════════════════════════╝${NC}"
echo ""

if [ ! -f .peers.pid ]; then
    echo -e "${YELLOW}No peers.pid file found${NC}"
    echo -e "${YELLOW}Attempting to kill all analog_codec_v42_hybrid processes...${NC}"
    pkill -f "analog_codec_v42_hybrid" || true
    echo -e "${GREEN}✓ Done${NC}"
    exit 0
fi

# Read PIDs
PIDS=($(cat .peers.pid))

echo -e "${YELLOW}Stopping peers gracefully...${NC}"
echo ""

for i in {0..4}; do
    PEER_NUM=$((i + 1))
    PID=${PIDS[$i]}

    if ps -p $PID > /dev/null 2>&1; then
        echo -e "  Stopping Peer $PEER_NUM (PID: $PID)..."
        kill -TERM $PID 2>/dev/null || true

        # Wait up to 5 seconds for graceful shutdown
        for j in {1..5}; do
            if ! ps -p $PID > /dev/null 2>&1; then
                echo -e "  ${GREEN}✓ Peer $PEER_NUM stopped${NC}"
                break
            fi
            sleep 1
        done

        # Force kill if still running
        if ps -p $PID > /dev/null 2>&1; then
            echo -e "  ${YELLOW}Force killing Peer $PEER_NUM${NC}"
            kill -9 $PID 2>/dev/null || true
        fi
    else
        echo -e "  ${YELLOW}Peer $PEER_NUM (PID: $PID) already stopped${NC}"
    fi
done

echo ""
echo -e "${GREEN}All peers stopped${NC}"

# Clean up PID file
rm -f .peers.pid
echo -e "${GREEN}Cleaned up .peers.pid${NC}"

echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo -e "${CYAN}  Network stopped successfully${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo ""
echo -e "Log files preserved in: ${YELLOW}logs/${NC}"
echo -e "Data files preserved in: ${YELLOW}data/${NC}"
echo ""
echo -e "To restart: ${YELLOW}./launch_5peers.sh${NC}"
echo ""
