#!/bin/bash
#
# local-fs1 monitor service
#

DESC="local-fs1 monitor service"
DAEMON="/bin/bash"
DAEMON_ARGS="/usr/local/lib/local-fs1-loop.sh"
PIDFILE="/var/run/local-fs1.pid"
LOGFILE="/var/log/local-fs1.log" # Optional: If you want to log the output of the script

# Ensure that log files exist and have correct permissions
touch $LOGFILE
chown root:root $LOGFILE
chmod 644 $LOGFILE

start() {
    echo "Starting $DESC..."
    if [ -f $PIDFILE ]; then
        echo "$DESC is already running."
        return 0
    fi
    # Using start-stop-daemon to manage the process
    # --start --pidfile $PIDFILE : specifies the PID file to create/check
    # --exec $DAEMON : the executable to run
    # --background : run the process in the background
    # --make-pidfile : create the PID file
    # --chdir / : change directory to root (optional, but good practice for daemons)
    # -- $DAEMON_ARGS : the arguments to pass to the daemon
    start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON --background --make-pidfile --chdir / -- $DAEMON_ARGS >> $LOGFILE 2>&1
    if [ $? -eq 0 ]; then
        echo "$DESC started successfully."
    else
        echo "$DESC failed to start."
        return 1
    fi
}

stop() {
    echo "Stopping $DESC..."
    if [ ! -f $PIDFILE ]; then
        echo "$DESC is not running."
        return 0
    fi
    start-stop-daemon --stop --pidfile $PIDFILE
    if [ $? -eq 0 ]; then
        echo "$DESC stopped successfully."
    else
        echo "$DESC failed to stop."
        return 1
    fi
}

status() {
    if [ -f $PIDFILE ]; then
        echo "$DESC is running."
        return 0
    else
        echo "$DESC is not running."
        return 1
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo "Usage: /etc/init.d/local-fs1 {start|stop|status|restart}"
        exit 1
        ;;
esac

exit 0