#!/bin/bash

# Source conf file with hack to remove sections
# (section is used by python AGI xivocc-determinate... using ConfigParser)
source <(grep -vE '\[.*\]' /etc/xivocc-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]}"
    export RSYNC_PASSWORD=$PASSWORD
    rsync --bwlimit=200 --remove-source-files --timeout=3 -z $FILE rsync://$USERNAME@$RECORDING_SERVER/recording/$FOLDER/
    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 check_and_clean_empty_file {
    if [ "$(sox --i -B $1)" == "0" ]; then
        log "Mixing is empty, deleting file"
        local FILE_NO_EXTEN="${1%.wav}"
        rm -f "$1" \
              "${FILE_NO_EXTEN}-in.raw" \
              "${FILE_NO_EXTEN}-out.raw"
        exit 2
    fi
}

function combine_raw_files_to_a_stereo_wav {
    FILE=$1
    FILE_NO_EXTEN="${FILE%.wav}"

    rm $FILE
    sox -t raw -r 8000 -e signed -b 16 -c 1 $FILE_NO_EXTEN-in.raw -t raw -r 8000 -e signed -b 16 -c 1 $FILE_NO_EXTEN-out.raw -M $FILE
    rm $FILE_NO_EXTEN-in.raw $FILE_NO_EXTEN-out.raw
}

log "File name:  $1"

MIXED_FILENAME=$1

check_and_clean_empty_file "$MIXED_FILENAME"
combine_raw_files_to_a_stereo_wav "$MIXED_FILENAME"
replicate "$MIXED_FILENAME"

