#!/bin/bash

set -u

PROCESS_NAME="${1:-}"

if [[ -z "$PROCESS_NAME" ]]; then
    echo "Usage: $0 <process_name>"
    exit 1
fi

case "$PROCESS_NAME" in
    game-tool)
        DIRECTORY_LOCATION="${HOME}/upload/image"
        ;;
    srv_mgt_go)
        DIRECTORY_LOCATION="${HOME}/srv_mgt"
        ;;
    *)
        echo "Unknown Process Name: $PROCESS_NAME"
        exit 1
        ;;
esac

PROCESS_PATH="${DIRECTORY_LOCATION}/${PROCESS_NAME}"
LOG_FILE="${DIRECTORY_LOCATION}/${PROCESS_NAME}.log"

if [[ ! -d "$DIRECTORY_LOCATION" ]]; then
    echo "Directory not found: $DIRECTORY_LOCATION"
    exit 1
fi

if [[ ! -x "$PROCESS_PATH" ]]; then
    echo "Process file not found or not executable: $PROCESS_PATH"
    exit 1
fi

get_pids() {
    pgrep -x "$PROCESS_NAME" 2>/dev/null || true
}

stop_process() {
    local pids
    pids="$(get_pids)"

    if [[ -z "$pids" ]]; then
        echo "Process not running: $PROCESS_NAME"
        return 0
    fi

    echo "Stopping process: $PROCESS_NAME, pid=$pids"
    for pid in $pids; do
        kill "$pid"
    done

    sleep 2

    pids="$(get_pids)"
    if [[ -n "$pids" ]]; then
        echo "Force killing process: $PROCESS_NAME, pid=$pids"
        for pid in $pids; do
            kill -9 "$pid"
        done
        sleep 1
    fi

    return 0
}

start_process() {
    cd "$DIRECTORY_LOCATION" || {
        echo "Failed to cd: $DIRECTORY_LOCATION"
        return 1
    }

    nohup "$PROCESS_PATH" >> "$LOG_FILE" 2>&1 &
    sleep 2

    local pids
    pids="$(get_pids)"
    if [[ -z "$pids" ]]; then
        echo "Start failed: $PROCESS_NAME"
        return 1
    fi

    echo "Started successfully: $PROCESS_NAME, pid=$pids"
    return 0
}

if [[ -n "$(get_pids)" ]]; then
    stop_process
    start_process
else
    start_process
fi
