#!/bin/bash
script_dir="$(cd "$(dirname "$0")" && pwd)" || exit 1
cd "$script_dir/.." || exit 1

PROCESS_NAME="dxprint"

echo "Verificare instante anterioare de $PROCESS_NAME..."

PIDS=$(pgrep -x "$PROCESS_NAME" || true)

if [ -n "$PIDS" ]; then
    echo "S-au gasit instante active (PID: $PIDS). Se opresc..."
    for pid in $PIDS; do
        kill -15 "$pid"
    done
    sleep 2
    REMAINING_PIDS=$(pgrep -x "$PROCESS_NAME" || true)
    if [ -n "$REMAINING_PIDS" ]; then
        echo "Procesul nu s-a oprit graceful. Se forteaza oprirea (SIGKILL)..."
        for pid in $REMAINING_PIDS; do
            kill -9 "$pid"
        done
    else
        echo "Procesul anterior a fost oprit cu succes."
    fi
else
    echo "Nu s-au gasit instante active."
fi

echo "Pornire instanta noua in background..."
nohup ./$PROCESS_NAME > /dev/null 2>&1 &
echo "Driverul a pornit cu PID $!."
sleep 1
exit 0
