#! /bin/sh
### BEGIN INIT INFO
# Provides:          piMooPCNd
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start and stop piMoo playlist change notifier
# Description:       starts and stops the piMoo playlist change notifier as a Daemon

# -- old SysV init script --
# -- must be placed at /etc/init.d/piMoo --

# for Debian users:
# copy this script to /etc/init.d/
# so you can easily control piMoo's playlist change notifier with the runlevel editor "rcconf" [1]
# e.g. to make it automatically launch at system start

# -- [1] since Debian "Trixie" use systemctl (rcconf is not available any longer) --
# cp more/runlevel_PCN_Debian /etc/init.d/piMooPCNd
# chmod u+x /etc/init.d/piMooPCNd
# -- required to make newly copied runlevel scripts accessible --
# systemctl daemon-reload
# -- then control like this --
# systemctl start piMooPCNd, systemctl status piMooPCNd or systemctl stop piMooPCNd
# -- making permanent --
# systemctl enable piMooPCNd or systemctl disable piMooPCNd

### END INIT INFO
# Author: Name <info@craft4fun.de>


LOGFILE="/var/log/piMooPCNd.log"

# actions
case "$1" in

    # -- ---------------------- --
    # -- for piMoo's own (web) control --

    run)
        if [ ! "$(pidof inotifywait)" ]
        then
          cd /var/www/html/piMoo/
          # sudo -u www-data /var/www/html/piMoo/cli_playlistChangeNotifier.php &
          /var/www/html/piMoo/cli_playlistChangeNotifier.php &
        fi
    ;;

    break)
      # pkill -x cli_playlistChangeNotifier.php
      pkill -f cli_playlistChangeNotifier.php
    ;;



    # -- -------------------------- --
    # -- for init runlevel handling --

    start)
      cd /var/www/html/piMoo/
      # sudo -u www-data /var/www/html/piMoo/cli_playlistChangeNotifier.php &
      /var/www/html/piMoo/cli_playlistChangeNotifier.php &
    ;;

    stop)
      # sudo -u www-data pkill -x cli_playlistChangeNotifier.php
      # pkill -x cli_playlistChangeNotifier.php
      pkill -f cli_playlistChangeNotifier.php
    ;;


    restart)
      echo "$(date): Restarting piMoo playlist change notifier..." >> "$LOGFILE"
      $0 stop >> "$LOGFILE" 2>&1
      if [ $? -ne 0 ]; then
          echo "$(date): Failed to stop piMoo playlist change notifier." >> "$LOGFILE"
          exit 1
      fi

      sleep 2
      $0 start >> "$LOGFILE" 2>&1
      if [ $? -ne 0 ]; then
          echo "$(date): Failed to start piMoo playlist change notifier after restart." >> "$LOGFILE"
          exit 1
      fi

      echo "$(date): Restart complete." >> "$LOGFILE"
    ;;


    *)
      echo "Usage: /etc/init.d/piMooPCNd {start|stop|restart}"
      exit 1
    ;;

esac

exit 0

