#!/usr/bin/env bash
set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
PID_FILE="$PROJECT_DIR/.dev.pid"

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

if [ ! -f "$PID_FILE" ]; then
    echo -e "${RED}Dev-Umgebung läuft nicht (keine PID-Datei).${NC}"
    exit 0
fi

STOPPED=0
ALREADY_DEAD=0

while read -r PID; do
    if kill "$PID" 2>/dev/null; then
        STOPPED=$((STOPPED + 1))
        echo -e "  ${YELLOW}▸${NC} Prozess $PID gestoppt"
    else
        ALREADY_DEAD=$((ALREADY_DEAD + 1))
    fi
done < <(tr ' ' '\n' < "$PID_FILE")

rm -f "$PID_FILE"

echo ""
if [ "$ALREADY_DEAD" -gt 0 ]; then
    echo -e "${YELLOW}  $ALREADY_DEAD Prozess(e) waren bereits beendet.${NC}"
fi
echo -e "${GREEN}Dev-Umgebung gestoppt. ($STOPPED Prozess(e) beendet)${NC}"
echo ""
