#!/bin/bash

# $Id$

function date_msg() {
	DATE=$(date '+%F %H:%M:%S.%N')
	DATE=${DATE#??}
	DATE=${DATE%?????}
	echo "[${DATE}] $(basename $0) ($$)" $@
}

if [ $# = 0 ]
then
  echo "Script to restart Logitech Media Server git code over and over again."
  echo "This might need to be done since the mysql-server is sometimes"
  echo "restarted due to upgrades and log-rotation and this causes"
  echo "Logitech Media Server to exit."
  echo
  echo "To stop Logitech Media Server git code, kill this script instead of the"
  echo "actual lms process."
  echo
  echo "Usage: $0 lms-binary lms-arguments"
  exit 1
fi

function clean_up {
  # Kill the daemon if it is running
  kill $SLIMPID
  date_msg "stopped." >> /var/log/lms/server.log
  exit
}

trap clean_up SIGINT SIGHUP SIGTERM

date_msg "started." >> /var/log/lms/server.log

while true
do
  # From the Bash Reference Manual:
  # When Bash receives a signal for which a trap has been set
  # while waiting for a command to complete, the trap will not
  # be executed until the command completes. When Bash is waiting
  # for an asynchronous command via the wait builtin, the reception
  # of a signal for which a trap has been set will cause the wait
  # builtin to return immediately with an exit status greater than
  # 128, immediately after which the trap is executed.

  "$@" --norestart > /dev/null 2>&1 &
  SLIMPID=$!

  # wait for the server to get started before wait()
  sleep 5

  wait $SLIMPID
  date_msg "Logitech Media Server git code died. Restarting." >> /var/log/lms/server.log

  # Normally, when the server realizes that the mysql-connection is gone,
  # the mysql server has already been started again. So no need to sleep
  # here.

done
