#!/bin/bash
docroot=/usr/local/emhttp                            # webGui root folder
nchan_pid=/var/run/nchan.pid                         # keeps list of nchan processes registered by GUI
disk_load=/var/local/emhttp/diskload.ini             # disk load statistics
nginx=/var/run/nginx.socket                          # nginx local access
status=http://localhost/pub/session?buffer_length=1  # nchan information about GUI subscribers
nchan_id=$(basename "$0")

# immediate kill command
if [[ $1 == kill ]]; then
  [[ -s $nchan_pid ]] || exit
  echo "Killing nchan processes..."
  while IFS=$'\n' read -r running; do
    name="${running##*/}"
    # kill all processes or single process
    if [[ -z $2 || $2 == ${name/:stop/} ]]; then
      echo "$name"
      pkill -f "$docroot/${running/:stop/}"
    fi
  done < $nchan_pid
  if [[ -z $2 ]]; then
    # remove pid file
    rm -f $nchan_pid $disk_load
  else
    # remove single entry
    sed -i "/$2/d" $nchan_pid
  fi
  exit
fi

start=$(date +%s)
while :; do
  # only act when GUI registered nchan processes are running
  if [[ -s $nchan_pid ]]; then
    # get number of GUI nchan subscribers
    subs=$(curl --unix-socket $nginx $status 2>/dev/null|grep -Pom1 'subscribers: \K\d+')
    if [[ -z $subs || $subs -eq 0 ]]; then
      sleep 5
      # steady state?
      subs=$(curl --unix-socket $nginx $status 2>/dev/null|grep -Pom1 'subscribers: \K\d+')
      if [[ -z $subs || $subs -eq 0 ]]; then
        now=$(date +%s)
        # log at 1 hour interval
        if [[ $((now-start)) -ge 3600 ]]; then
          logger -t $nchan_id -- "Stop running nchan processes"
          start=$now
        fi
        # kill GUI registered nchan processes
        while IFS=$'\n' read -r running; do
          pkill -f $docroot/${running/:stop/}
        done < $nchan_pid
        # empty GUI registered list & statistics
        rm -f $nchan_pid $disk_load
      fi
    fi
  fi
  # check every 30 seconds
  sleep 30
done &
disown %%
