#!/bin/bash
#
# Listing 3.
# Queue.sh
# 

echo ------------------------------
echo $0
echo ------------------------------

MAILFILE=$HOME/mail_from_yahoo.txt
      QUEUE=$HOME/queue.txt
 QUEUE_PASS=$HOME/queue_pass.txt
QUEUE_CHECK=$HOME/queue_check.txt
DELIM1="+"

export PATH=$PATH:/bin:/sbin:/usr/bin

[[ -e $MAILFILE  ]]  || { echo $0:$MAILFILE  does not exist ; exit 1; }
[[ -s $MAILFILE  ]] ||  { echo $0:$MAILFILE  is empty       ; exit 1; }



#######Functions################

function check_q_size {

QUEUE_SIZE=$(cat $QUEUE | wc -l)
MAX_CMD="10"

if [[ $QUEUE_SIZE -gt "$MAX_CMD" ]]; then
  echo too many in the Q 
  exit 1
fi

}



function seeq {

if [[ -e $QUEUE  ]];then
 echo
 echo Q:contents of Q
 cat $QUEUE
 echo 
else
  echo Q:$QUEUE  does not exist
fi

if [[ -e $QUEUE_PASS ]];then
 echo
 echo QP:contents of Qpass
 cat $QUEUE_PASS
 echo 
else
  echo QP:$QUEUE_PASS does not exist 
fi

if [[ -e $QUEUE_CHECK  ]];then
 echo
 echo QC:contents of Qcheck
 cat $QUEUE_CHECK
else
  echo QC:$QUEUE_CHECK  does not exist
fi


}


########Script###################

while read LINE; do 

        #A)Does Mail start with Subject:Cmd??
       if echo $LINE | grep -i Subject |grep -i Cmd > /dev/null ; then

          if [[ !  -s $QUEUE  ]]; then

            ID=1

          else

           ID=$(cat $QUEUE | tail -n 1 | cut -d "$DELIM1" -f1)
           ID=$(( $ID + 1 ))

          fi

          PASS=$(./rand.pl)
          COMMAND=$(echo $LINE | grep -i subject | cut -d "$DELIM1" -f2 | tr  '[:upper:]' '[:lower:]')
          HOST=$(echo $LINE | grep -i subject | cut -d "$DELIM1" -f3 | tr  '[:upper:]' '[:lower:]')

          echo $ID$DELIM1$PASS$DELIM1$COMMAND$DELIM1$HOST >> $QUEUE

          check_q_size


        #B)Is field starting with a number?
       elif echo $LINE | grep -i Subject | grep [0-9] > /dev/null ; then

            ID=$(echo $LINE | grep -i subject | sed s/" "//g | cut -d "$DELIM1" -f1 | cut -d ":" -f2)
          PASS=$(echo $LINE | grep -i subject | cut -d "$DELIM1" -f2)

          echo $ID$DELIM1$PASS >> $QUEUE_PASS  


       fi



done < $MAILFILE

seeq

rm -v $MAILFILE
echo
