#!/bin/sh

###########################################################################
#
# start-fancontrol.sh
#
# Dell PowerEdge Fan Controller Launcher
# Version : 2.0
# Platform : TrueNAS
#
# Description:
#   Starts fancontrol.sh as a background daemon.
#   Prevents multiple instances from running.
#   Creates and maintains the PID file.
#
# License : MIT
#
# Author : Jack Bamford
# Date   : July 2026
#
###########################################################################

SCRIPT="/root/scripts/fancontrol.sh"
PIDFILE="/var/run/fancontrol.pid"
LOGFILE="/var/log/fancontrol.log"

if [ -f "$PIDFILE" ]; then
    PID="$(cat "$PIDFILE" 2>/dev/null)"

    if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
        logger "Fan Controller already running with PID $PID"
        exit 0
    fi

    rm -f "$PIDFILE"
fi

nohup "$SCRIPT" >>"$LOGFILE" 2>&1 &

PID=$!
echo "$PID" >"$PIDFILE"

logger "Fan Controller launched with PID $PID"

exit 0
