#!/bin/bash
# mix two soundpaths to one outputrecording file.
# This script receives 3 parameters:
#
# $1: hostname-pid-uniqueid-callseq-flags-in.WAV
# $2: hostname-pid-uniqueid-callseq-flags-out.WAV
# $3: hostname-pid-uniqueid-callseq-flags.WAV
#
# callseq can be 01-99 for each next conversation within a session
# flags = 10 means keep only the -in.WAV
#         12 means keep both
#         02 means keep only the -out.WAV
#         00 means lose both recordings

# mixmonitor mixes together the -in and -out channels to one WAV
#            calculates the checksum on it, and stores that into parm5 of the type 61 callhist record.

logger $0: $*
if [ -x /usr/bin/ionice ]
then
  /usr/bin/ionice -c2 -n7 -p$$
fi

renice +19 $$ > /dev/null

if [ $# != 3 ]
then
  echo usage: $0 file1 file2 outfile
  exit 1
fi

TEMPDIR="/tmp/mixmonitor"

# Create temp directory if it does not exists.
if [ ! -d $TEMPDIR ]
then
	mkdir -p $TEMPDIR
fi

CALLSEQ=${3: -9:2}
FLAGS=${3: -6:2}
EXT=${3: -10: 10}
SESSIONID=`basename $3 $EXT`

# stereo mixing does not work yet
#sox -c 1 $1 -c 2 $$-left.WAV pan -1 
#sox -c 1 $2 -c 2 $$-right.WAV pan 1
#soxmix $$-left.WAV $$-right.WAV $3

case $FLAGS in
  10)
      if [ -f $3 ]
      then
        sox "$3" "$1" $TEMPDIR/mixmonitor2.$$.WAV
        mv -f $TEMPDIR/mixmonitor2.$$.WAV "$3"
      else 
        cp "$1" "$3"
      fi
    ;;
  12)
      if [ -f $3 ]
      then
        soxmix "$1" "$2" $TEMPDIR/mixmonitor.$$.WAV
        sox "$3" $TEMPDIR/mixmonitor.$$.WAV $TEMPDIR/mixmonitor2.$$.WAV
        rm -f $TEMPDIR/mixmonitor.$$.WAV
        mv -f $TEMPDIR/mixmonitor2.$$.WAV "$3"
      else
        soxmix "$1" "$2" "$3"
      fi
    ;;
  02)
      if [ -f $3 ]
      then
        sox "$3" "$1" $TEMPDIR/mixmonitor2.$$.WAV
        mv -f $TEMPDIR/mixmonitor2.$$.WAV "$3"
      else 
        cp "$1" "$3"
      fi
    ;;
  00)
      # do nothing
    ;;
esac

rm -f "$1" "$2"

# no checksums yet.
#WAVDIR="/var/spool/asterisk/monitor/__wavs__"
#mkdir -p $WAVDIR
#chgrp apache $WAVDIR
#chmod 0775 $WAVDIR
#
#SHA1SUM=`sha1sum $3 | cut -d' ' -f1`
#
#echo "update callhist set parm5= '$SHA1SUM' where sessionid = '$SESSIONID' and uniqueid = $CALLSEQ" | psql -qt -Uastium
