#!/bin/bash

# Load variables from config file (ignoring INI sections)
source <(grep -vE '^\[.*\]' /etc/recording.conf)

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

function replicate {
    local file="$1"
    log "Replicating file $file"

    # Sync to target (local or remote)
    rsync --remove-source-files -z "$file" /app/recording/
    if [ $? -eq 0 ]; then
        log "Replication of $file completed"
    else
        # On failure, move to failed dir
        rsync --remove-source-files -a "$file" "$FAILED_DIR/$(basename "$file")"
        log "Replication failed, moved $file to $FAILED_DIR"
    fi
}

# === Main ===
FILE="$1"
log "Received mixed recording: $FILE"

# Convert to MP3
MP3_FILE="${FILE%.wav}.mp3"
ffmpeg -i "$FILE" -codec:a libmp3lame -qscale:a 4 "$MP3_FILE"
if [ $? -eq 0 ]; then
    log "MP3 conversion successful: $MP3_FILE"
    rm -f "$FILE"
    replicate "$MP3_FILE"
else
    log "MP3 conversion failed, replicating WAV instead"
    replicate "$FILE"
fi

