#!/bin/bash

LOG_DIR="/var/log/move"
LOG_FILE="$LOG_DIR/odd-naming-move-$(date '+%Y%m%d-%H%M%S').log"

# Log function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Check if ffmpeg is processing files in the anime directory
check_ffmpeg_running() {
    if pgrep -f "ffmpeg.*/home/aaron/Videos/anime/" > /dev/null; then
        return 0  # ffmpeg is running
    else
        return 1  # ffmpeg is not running
    fi
}

# Exit if ffmpeg is currently processing anime videos
if check_ffmpeg_running; then
    log "FFmpeg is currently processing files in /home/aaron/videos/anime/ - exiting to avoid conflicts"
    exit 0
fi

ANIME_DIR="/mnt/truenas/media/Anime/"
SOURCE=(        "Trigun Stargaze/Season 02/"    "Fate-strange Fake/Season 01/"              "Frieren Beyond Journeys End/Season 02/")
DESTINATION=(   "Trigun Stampede/Season 02/"    "Fate - Strange Fake (2023)/Season 01/"     "Frieren/Season 02/")

for i in "${!SOURCE[@]}"; do
    src="${ANIME_DIR}${SOURCE[$i]}"
    dest="${ANIME_DIR}${DESTINATION[$i]}"

    # Check if source directory exists
    if [ ! -d "$src" ]; then
        log "Warning: Source directory does not exist: $src"
        continue
    fi

    # Check if source directory contains files
    if [ -z "$( ls -A "$src" )" ]; then
        log "Info: Source directory is Empty, Skipping: $src"
        continue
    fi

    mkdir -p "$dest"

    # Extract the show names from the paths (remove trailing "/Season XX/")
    src_show=$(basename "$(dirname "$src")")
    dest_show=$(basename "$(dirname "$dest")")

    log "Processing: $src_show -> $dest_show"

    # Move and rename all files from source to destination
    for file in "$src"*mkv; do
        if [ -f "$file" ]; then
            filename=$(basename "$file")
            new_filename="${filename/$src_show/$dest_show}"
            log "  Moving: $filename"
            log "      to: $new_filename"
            mv -n "$file" "$dest$new_filename"
        fi
    done
done

log "Done!"
