#!/bin/bash
VARLOG=/var/log/minerva

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

if [ $# -le 1 ]; then
  echo "Usage: $0 <device> <start|next|more|current|stop|list> [type] [max items]"
  echo "       Note: this is a synchronous method"
  exit -1
fi

MINBASE=/usr/local/minerva
VARBASE=$VARLOG/manifest

ETCBASE=$MINBASE/etc/manifest

DEVICE=$1
COMMAND=$2
TYPE=$3
PARAMETER=$4

DEVICE=`$MINBASE/bin/finddev manifest $*`
if [ $? == 0 ]; then
  echo $DEVICE
  exit 0;
fi


case "$COMMAND" in
  init)
     mkdir $VARBASE 2>/dev/null
     touch $VARBASE/curr
     chmod -R ugo+rw $VARBASE
     exit 0
     ;;

  enumdev)
     $MINBIN/enumdev manifest
     exit $?
     ;;

  list)
     ls -1 $ETCBASE
     ;;

  start)
     $0 $DEVICE stop
     MAXCOUNT=$4
     if [ "$MAXCOUNT" == "" ]; then
        MAXCOUNT=5
     fi
     if [ -f $ETCBASE/$TYPE/onstart ]; then
        $ETCBASE/$TYPE/onstart $DEVICE $PARAMETER
     fi
     COUNT=0
     EXITCODE=0
     echo next > $VARBASE/cmd
     while [ "$EXITCODE" -eq 0 ]; do
         echo $TYPE > $VARBASE/curr
         echo $COUNT > $VARBASE/count

         $ETCBASE/$TYPE/onnext $DEVICE $COUNT $PARAMETER &
         PID=$!
         echo $PID > $VARBASE/pid
         wait $PID 2>/dev/null
         EXITCODE=$?

         NEXTCMD=`cat $VARBASE/cmd`
         if [ "$NEXTCMD" == "next" ]; then
            # let it just loop around
            NEXTCMD=$NEXTCMD

         elif [ "$NEXTCMD" == "more" ]; then
            if [ -f $ETCBASE/$TYPE/onmore ]; then
               $ETCBASE/$TYPE/onmore $DEVICE $COUNT $PARAMETER
               EXITCODE=$?
            fi
            echo next > $VARBASE/cmd

         elif [ "$NEXTCMD" == "stop" ]; then
            EXITCODE=1
         fi

         # terminate at end (rem: we started from 0, therefore use -ge)
         COUNT=$(($COUNT+1))
         if [ $COUNT -ge $MAXCOUNT ]; then 
            EXITCODE=1
         fi
     done 

     if [ -f $ETCBASE/$TYPE/onstop ]; then
        $ETCBASE/$TYPE/onstop $DEVICE $PARAMETER
     fi
     exit 0
     ;;

  current)
     if [ -f $VARBASE/curr ]; then
       head -n 1 $VARBASE/curr
       exit 0
     else
       exit 1
     fi
     ;;

  next|stop)
     echo $COMMAND > $VARBASE/cmd
     TYPE=`head -n 1 $VARBASE/curr`
     if [ -f $ETCBASE/$TYPE/terminate ]; then
        $ETCBASE/$TYPE/terminate $DEVICE
     elif [ -f $VARBASE/pid ]; then
        PID=`cat $VARBASE/pid`
        kill -9 $PID 2>/dev/null
        sleep 1
     fi
     ;;

  more)
     echo more > $VARBASE/cmd
     exit 0
     ;;
esac

