#!/bin/bash

# ANSC Customization for Recording
# Stereo feature was removed for ANSC.
# So using a custom synchronization file which does not handle the mixing etc.

# 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"
        rm $1
        exit 2
    fi
}

log "File name:  $1"

MIXED_FILENAME=$1

check_and_clean_empty_file "$MIXED_FILENAME"
replicate "$MIXED_FILENAME"

