#!/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}
TAIL=${3: -10: 10}
EXT=${3: -3: 3}
SESSIONID=`basename $3 $TAIL`
NEW3=`echo $3 | sed -e 's@ramdisk/@@'`

case $FLAGS in
  10)
      if [ -f ${NEW3} ]
      then
        sox "${NEW3}" "$1" $TEMPDIR/mixmonitor2.$$.$EXT
        mv -f $TEMPDIR/mixmonitor2.$$.$EXT "${NEW3}"
      else 
        cp "$1" "${NEW3}"
      fi
    ;;
  12)
      if [ -f ${NEW3} ]
      then
        sox -c1 "$1" -c2 $TEMPDIR/mixmonitor-left.$$.$EXT pan -1
        sox -c1 "$2" -c2 $TEMPDIR/mixmonitor-right.$$.$EXT pan 1
        soxmix -c2 $TEMPDIR/mixmonitor-left.$$.$EXT -c2 $TEMPDIR/mixmonitor-right.$$.$EXT -c2 $TEMPDIR/mixmonitor.$$.$EXT
        sox "${NEW3}" $TEMPDIR/mixmonitor.$$.$EXT $TEMPDIR/mixmonitor2.$$.$EXT
        rm -f $TEMPDIR/mixmonitor.$$.$EXT
        mv -f $TEMPDIR/mixmonitor2.$$.$EXT "${NEW3}"
        rm -f $TEMPDIR/mixmonitor-left.$$.$EXT $TEMPDIR/mixmonitor-right.$$.$EXT
      else
	if test "${EXT}" = "wav"; then
        	sox -c1 "$1" -c2 $TEMPDIR/mixmonitor-left.$$.$EXT pan -1
        	sox -c1 "$2" -c2 $TEMPDIR/mixmonitor-right.$$.$EXT pan 1
        	soxmix $TEMPDIR/mixmonitor-left.$$.$EXT $TEMPDIR/mixmonitor-right.$$.$EXT "${NEW3}"
      		rm -f $TEMPDIR/mixmonitor-left.$$.$EXT $TEMPDIR/mixmonitor-right.$$.$EXT
	else
		soxmix "$1" "$2" "${NEW3}"
	fi
      fi
    ;;
  02)
      if [ -f ${NEW3} ]
      then
        sox "${NEW3}" "$1" $TEMPDIR/mixmonitor2.$$.$EXT
        mv -f $TEMPDIR/mixmonitor2.$$.$EXT "${NEW3}"
      else 
        cp "$1" "${NEW3}"
      fi
    ;;
  00)
      # do nothing
    ;;
esac

rm -f "$1" "$2"

