#!/bin/sh
# $Id: rc.icecast.new,v 1.2 2010/09/15 14:49:47 root Exp root $
# ---------------------------------------------------------------------------
#
# /etc/rc.d/rc.icecast
#      This shell script takes care of starting and stopping
#      the icecast server, plus the "ices" source client.
# Author:
#      Eric Hameleers <alien@slackware.com>
#

[ -x /usr/bin/icecast ] || exit 0

start() {
      # Start daemons.
      echo -n "Starting icecast:  /usr/bin/icecast -c /etc/icecast/icecast.xml "
      if [ ! -f /etc/icecast/icecast.xml ]; then
        echo "... configuration file not found!"; exit 0
      fi
      /usr/bin/icecast -b -c /etc/icecast/icecast.xml
      echo
      if [ -x /usr/bin/ices ]; then
        sleep 3
        echo -n "Starting ices:  /usr/bin/ices -v "
        /usr/bin/ices -v
        echo
      fi
}
stop() {
      # Stop daemons.
      if [ -x /usr/bin/ices ]; then
        echo -n "Shutting down ices: "
        killall -TERM ices
      fi
      echo -n "Shutting down icecast: "
      # Rude: killall -TERM
      killall -TERM icecast
      echo
}
status() {
  PIDS1=$(pidof icecast)
  PIDS2=$(pidof ices)
  if [ "x$PIDS1" = "x" ]; then
    echo "icecast is not running!"
  else
    echo "icecast is running at pid(s) ${PIDS1}."
  fi
  if [ "x$PIDS2" = "x" ]; then
    echo "ices is not running!"
  else
    echo "ices is running at pid(s) ${PIDS2}."
  fi
}
current() {
  if [ -f /var/state/ices/ices.cue ]; then
    desc=("Filename:     " \
          "Filesize:     " \
          "Bitrate:      " \
          "Playing time: " \
          "% elapsed:    " \
          "Ices index:   " \
          "Artist:       " \
          "Song Title:   ")
    index=0
    while read cueline; do
      echo "${desc[$index]} $cueline"
      index=$(expr $index + 1)
    done < /var/state/ices/ices.cue
  else
    echo "I found no running 'ices' icecast source client!"
  fi
}
next() {
  if [ ! -f /var/state/ices/ices.pid ]; then
    echo "Can't skip to next track... can't find ices source client."
  else
    echo "Skipping to next track in playlist..."
    kill -USR1 $(cat /var/state/ices/ices.pid)
  fi
}

# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        stop
        sleep 2
        start
        ;;
  status)
        status
        ;;
  next)
        next
        ;;
  current)
        current
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart|status|current|next}"
        ;;
esac

exit 0
