#! /bin/bash
#
# thomas@linuxmuster.net
# 20250326
#

DESC="tmux multicast session"

# lmn7 specific paths
source /usr/share/linuxmuster/helperfunctions.sh || exit 1
INTERFACE="$(LANG=C ip route show | grep ^default | awk '{ print $5 }')"
SERVERIP="$serverip"
DAEMON=$LINBOSHAREDIR/linbo-mcasthelper.sh

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

# read cmdline
action="$1"

# default values for udpcast
PORTBASE=9000
MINCLIENTS=16
MINSECONDS=60
MAXSECONDS=90

# override values for udpcast
. /etc/default/linbo-multicast || exit 1

# path to multicast filelist
MULTICASTLIST=$LINBODIR/multicast.list

images="$(find "$LINBODIR" -maxdepth 1 -name "*.cloop" ; \
  find "$LINBOIMGDIR" -maxdepth 2 -name "*.q[cd][oi][wf][2f]")"

create_multicast_list() {
  echo -n "Creating multicast.list"
  local i
  local image
  local p
  [ -e "$MULTICASTLIST" ] && mv $MULTICASTLIST $MULTICASTLIST.old
  [ -e "${MULTICASTLIST}.tmp" ] && rm -f "${MULTICASTLIST}.tmp"
  p=$PORTBASE
  for i in $images; do
    image="$(basename "$i")"
    echo "$image $SERVERIP:$p" >> $MULTICASTLIST
    echo "$i" "$SERVERIP:$p" >> ${MULTICASTLIST}.tmp
    p=$(( $p + 2 ))
  done
  echo .
}

start() {
  if [ -z "$images" ]; then
    echo "There exist no images yet!"
    rm -f "${MULTICASTLIST}*"
    exit 0
  fi

  create_multicast_list

  local imgdir
  local imgfile
  local session
  while read file serverport relax; do
    port="${serverport##*:}"
    if [ -s "$file" ]; then

      imgdir="$(dirname "$file")"
      imgfile="$(basename "$file")"
      session="${imgfile//./_}_mcast"
      cd "$imgdir"

      # start daemon stuff
      echo -n "Starting $DESC $session ... "

      if linbo-multicast status | grep -qw "$session"; then
        echo "already running. Skipped!"
        continue
      fi

      LOGFILE="$LINBODIR/log/${session}.log"

      tmux new -ds "$session" "$DAEMON $INTERFACE $port $MINCLIENTS $MINSECONDS $MAXSECONDS $imgfile $LOGFILE ; exec $SHELL"
      sleep 1
      if linbo-multicast status | grep -qw "$session"; then
        RC=0
        echo "done!"
      else
        RC=1
        echo "failed!"
      fi

    fi
  done < "${MULTICASTLIST}.tmp"
  rm -f "${MULTICASTLIST}.tmp"
}

stop(){
  local session
  linbo-multicast status | awk -F\: '{print $1}' | while read session; do
    echo -n "Stopping $DESC $session ... "
    tmux kill-session -t "$session" ; RC="$?"
    if [ "$RC" = "0" ]; then
      echo "done!"
    else
      echo "failed!"
    fi
  done
}

status(){
  tmux list-sessions | grep _mcast
}

case "$action" in
  start) start ;;
  stop) stop ;;
  restart)
    stop
    start ;;
  status) status ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}" >&2
    exit 1 ;;
esac

exit 0
