#!/bin/bash

# Base directory for all operations
BASE_DIR="$HOME/Dropbox/__INBOX_RECIEVING/__AUDIO-IN"
INPUT_DIR="$BASE_DIR/_01_Processing"
OUTPUT_DIR="$BASE_DIR/_02_Converted_MP3"
LOGS_DIR="$BASE_DIR/_LOGS"

# Ensure logs directory exists
mkdir -p "$LOGS_DIR"

# Move log file outside of processing directory
LOG_FILE="$LOGS_DIR/conversion_log.txt"

LOCKFILE="/tmp/my_script.lock"
if [ -e "$LOCKFILE" ]; then
    echo "Script is already running."
    exit 1
fi
touch "$LOCKFILE"
trap "rm -f $LOCKFILE" EXIT


echo "Watching for new files..."

fswatch -0 -e "\.DS_Store$" "$INPUT_DIR" | while IFS= read -r -d $'\0' file; do
# Check if the file still exists
    if [ ! -f "$file" ]; then
        echo "$(date): Ignoring deleted or moved file: $file" | tee -a "$LOG_FILE"
        continue
    fi

    echo "$(date): Detected file: $file" | tee -a "$LOG_FILE"
    
# Use Python (eyeD3) to validate MP3 files
    is_valid_mp3=$(/Users/bertm/Dropbox/__INBOX_RECIEVING/x-Scripts/audio_env/bin/python3 - <<EOF
import eyed3
try:
    audio = eyed3.load("$file")
    if audio and audio.info:
        print("Valid_MP3. Continuing the process…")
    else:
        print("INVALID_MP3")
except:
    print("INVALID_MP3")
EOF
)

if [[ "$file" =~ \.(mp4|m4a|mp3|aifc|aiff)$ ]]; then
    echo "$file is a video/audio file and will be converted to MP3." | tee -a "$LOG_FILE"
    filename=$(basename "$file")
    filename_no_ext="${filename%.*}"
    output_file="$OUTPUT_DIR/${filename_no_ext}.mp3"

    echo "Converting to MP3..." | tee -a "$LOG_FILE"
    ffmpeg -i "$file" -vn -acodec libmp3lame -q:a 2 "$output_file" 2>> "$LOG_FILE"

    if [ $? -eq 0 ]; then
        echo "$(date): Successfully converted $filename to MP3." | tee -a "$LOG_FILE"
        rm "$file"
        echo "File has moved on to next step"
    else
        echo "Error: Failed to convert $filename" | tee -a "$LOG_FILE"
    fi

    elif [[ "$file" =~ \.mp3$ ]]; then
        # Validate MP3 before processing
        if [[ "$is_valid_mp3" == "VALID_MP3" ]]; then
            echo "$file is a valid MP3 and will be processed." | tee -a "$LOG_FILE"
            mv "$file" "$OUTPUT_DIR/"
        else
            echo "Error: $file is NOT a valid MP3. Attempting to fix..." | tee -a "$LOG_FILE"

            # Attempt to rebuild the MP3
            fixed_file="${file%.*}_fixed.mp3"

if [[ "$file" =~ \.(aifc|aiff)$ ]]; then
    echo "Converting AIFC to MP3..." | tee -a "$LOG_FILE"
    ffmpeg -i "$file" -acodec libmp3lame -q:a 2 "$output_file" 2>> "$LOG_FILE"
else
    ffmpeg -i "$file" -vn -acodec libmp3lame -q:a 2 "$output_file" 2>> "$LOG_FILE"
fi
            ffmpeg -i "$file" -acodec copy "$fixed_file" 2>> "$LOG_FILE"

            if [ -f "$fixed_file" ]; then
                echo "$(date): Successfully fixed MP3. Moving fixed file." | tee -a "$LOG_FILE"
                mv "$fixed_file" "$OUTPUT_DIR/"
                rm "$file"
            else
                echo "Error: Could not fix MP3. Skipping." | tee -a "$LOG_FILE"
            fi
        fi      
    else
        echo "Error: Something weird is going on. $file is not a recognized audio or video file." | tee -a "$LOG_FILE"
    fi
     echo "MP3 Process Complete."
done