#!/bin/bash

  # first test that phone system is idle
  # and not in the middle of recording a call

ps -a > /home/phone/sh/proc

if grep -q ttyS4 /home/phone/sh/proc

then
  # vgetty is in use and phone is recording
  echo "phone is in use"

exit 1

else

  # check for new messages for box 400
 
 if [ ! -f /home/phone/incoming/400* ]

 then # new message for box 400 does not exist  
 echo "no new message"

 exit 1

    else

      for ITEM in $(ls /var/spool/voice/incoming/400*)

      do
          # remove msg if hangup
            filesize=`ls -ld $ITEM | cut -c31-41`
           
              if [ $filesize -le 2500 ]
              then rm $ITEM
              echo they hung up            
              exit 1

           else 
               
         # convert from rmd format to wav
         rmdtopvf $ITEM | pvfspeed -s 8000 | pvftowav > $ITEM.wav

         # convert wav message to .mp3  for streaming
         # renamed by timestamp
         NEWNAME=msg$(date +%b%d-%H%M%S)_400.mp3
         MSGNAME=$(date +%b%d-%H%M)_uk_sparrow_line
         
         /usr/local/bin/lame -h --preset studio --tt $MSGNAME --ta "bit uphone 442079870655" $ITEM.wav $NEWNAME
         
         # move new message out of incoming dir to msgs400 directory
         mv $NEWNAME /var/spool/voice/incoming/msgs400/

         #cleanup
         rm $ITEM.wav
         rm $ITEM 
       fi        
    done
         
  fi
fi

           # finally, upload todays messages to streaming server
           # using scp, ssh-keygen, ssh-agent, keychain

           LINKSSRC=/var/spool/voice/incoming/msgs400/msg*
           LINKSDEST=user@server:~/htdocs/audio/uphone/sparrow/

           scp $LINKSSRC $LINKSDEST

          mv /var/spool/voice/incoming/msgs400/msg* /var/spool/voice/incoming/msgs400/done/


