#!/bin/bash
CONFIG_FILE="/etc/seekdb/seekdb.cnf"
BASE_DIR="/var/lib/seekdb"

# Function to read base-dir from configuration file (consistent with start script)
read_base_dir_from_config() {
    if [ -f "$CONFIG_FILE" ]; then
        while IFS= read -r line; do
            # Skip empty lines and comments
            [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue

            key="${line%%=*}"
            value="${line#*=}"

            # Trim whitespace
            key="$(echo "$key" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
            value="$(echo "$value" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"

            if [ "$key" = "base-dir" ]; then
                BASE_DIR="$value"
                echo "Using base-dir from config: $BASE_DIR"
                return 0
            fi
        done < "$CONFIG_FILE"
    fi
    return 1
}

read_base_dir_from_config

if [ -f "$BASE_DIR/run/daemon.pid" ]; then
    pid=$(cat "$BASE_DIR/run/daemon.pid")
    kill -9 "$pid" 2>/dev/null || true
fi

if [ -f "$BASE_DIR/run/obshell.pid" ]; then
    pid=$(cat "$BASE_DIR/run/obshell.pid")
    kill -9 "$pid" 2>/dev/null || true
fi

if [ -f "$BASE_DIR/run/seekdb.pid" ]; then
    pid=$(cat "$BASE_DIR/run/seekdb.pid")
    kill -9 "$pid" 2>/dev/null || true
fi

systemd-notify "STATUS=seekdb is down"