#!/bin/bash

# Source conf file with hack to remove sections
# (section is used by python AGI xivocc-determinate... using ConfigParser)
source <(grep -vE '\[.*\]' /etc/vinci-recording.conf)

function log {
    date=`date +'%Y-%m-%d %H:%M:%S'`
    echo "$date $1" >> $LOG_FILE
}

function replicate {
    FILE=$1
    REGEX="([^-]+)-.+"

    log "Replicating file $FILE"

    [[ `basename $FILE` =~ $REGEX ]]
#    FOLDER="${BASH_REMATCH[1]}"
    FOLDER="xivo"
    export RSYNC_PASSWORD=$PASSWORD
    rsync --remove-source-files -z $FILE /app/recording/
    if [ $? -eq 0 ]
    then
        log  "Replication of $FILE completed"
    else
        rsync --remove-source-files -a $FILE $FAILED_DIR/`basename $FILE`
        log "Replication failed, writing $FILE to failed dir"
    fi
}

function mix {
    log "Mixing in and out streams ($1, $2) into $3)"
        sox -M $1 $2 -r 16000 -C 64 $3
    if [ $? -eq 0 ]
    then
        log "Mixing completed"
        rm $1 $2
    else
        log "Mixing failed, installation needs to be checked"
        exit 126
    fi
}


log "First argument:  $1"
log "Second argument: $2"
log "Third argument:  $3"

MIXED_FILENAME=$3
LEFT_IN_FILE=$1
RIGHT_OUT_FILE=$2
AUDIO=${MIXED_FILENAME::-3}"mp3"

mix $LEFT_IN_FILE $RIGHT_OUT_FILE $AUDIO
replicate $AUDIO

