#!/bin/bash

MINBIN=/usr/local/minerva/bin
PAUSELOG=/var/log/minerva/pmedia
VARLOG=/var/log/minerva

date +"%F %H:%M CMD $0 $*" >>$VARLOG/bearskin/`basename $0`

DEVICE=$1
COMMAND=$2

if [ "$COMMAND" == "init" ]; then
   echo null >$PAUSELOG
   exit 0;
fi

# The only command is "toggle"

# NOTE: mpg123 has been removed as its use is deprecated in favour
# of the bearskin mp3player command

if [ -f $PAUSELOG ]; then
   # We resume previously paused media...

   MEDIA=`cat $PAUSELOG`

   echo $MEDIA | grep cd > /dev/null
   if [ $? == 0 ]; then
      $MINBIN/cdplayer $DEVICE resume
      EXIT=1;
   fi
   
   echo $MEDIA | grep mp3 > /dev/null
   if [ $? == 0 ]; then
      $MINBIN/mp3player $DEVICE resume
      EXIT=1;
   fi

   echo $MEDIA | grep mpg123 > /dev/null
   if [ $? == 0 ]; then
      killall -18 mpg123
      EXIT=1;
   fi

   if [ "$EXIT" == 1 ]; then
      echo null >$PAUSELOG
      exit 0;
   fi
fi

# nothing is currently paused,then
echo null >$PAUSELOG

#
# see what's running, and pause it
# (if there's > 1 the log breaks, TODO?)
#
if [ "`$MINBIN/cdplayer $DEVICE isplaying`" == "1" ]; then
   $MINBIN/cdplayer $DEVICE pause
   echo cd >>$PAUSELOG
fi

if [ "`$MINBIN/mp3player $DEVICE isplaying`" == "1" ]; then
   $MINBIN/mp3player $DEVICE pause
   echo mp3 >>$PAUSELOG
fi

#if [ "`pgrep mpg123`" != "" ]; then
   #killall -6 mpg123
   #echo mpg123 >>$PAUSELOG
#fi


