#!/bin/bash

# Configuration for Orion O6
SYNC_FOLDER="/home/seedbox-sync/"
SYNC_TMP_DOWNLOAD_FOLDER="${SYNC_FOLDER}Downloads"
SERIES_FOLDER="/home/film/Series/"
DRY_RUN=false

# Change to a neutral directory to avoid 'find' errors if started from a restricted path
cd /

LN_PATH=$(which ln)
MKDIR_PATH=$(which mkdir)

while [[ $# -gt 0 ]]; do
    case "$1" in
        -n|--dry-run)
            DRY_RUN=true
            shift
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1
            ;;
    esac
done

# Ensure Series folder exists to avoid errors
if [ ! -d "${SERIES_FOLDER}" ]; then
    echo "⚠️  Series folder ${SERIES_FOLDER} does not exist. Skipping sorting."
    exit 0
fi

find "${SERIES_FOLDER}" -maxdepth 1 -mindepth 1 -type d -print0 |
while IFS= read -r -d '' SerieFolder
do
    SerieName=$(basename "${SerieFolder}")
    # Escape spaces for regex
    SearchPattern=$(echo "${SerieName}" | sed 's/ /\.\?/g')
    echo -e "Searching for Serie : ${SerieName}"

    # Find files in sync folder matching the serie name, excluding Downloads
    find "${SYNC_FOLDER}" -mindepth 1 \( -path "${SYNC_TMP_DOWNLOAD_FOLDER}" -prune \) -o -type f ! -name ".*" -iregex ".*${SearchPattern}.*" -print0 |
    while IFS= read -r -d '' EpisodePath
    do
        EpisodeFile=$(basename "${EpisodePath}")
        EpisodeExt=${EpisodeFile##*.}
        
        # Extract Season and Episode
        EpisodeSeason=$(echo "${EpisodeFile}" | sed 's|.*[Ss]\([0-9]\+\)[^0-9].*|0\1|g' | sed 's|^0\+||g')
        EpisodeNumberRaw=$(echo "${EpisodeFile}" | sed 's|.*[Ee]\([0-9]\+\)[^0-9].*|0\1|g' | sed 's|^0\+||g')

        if [[ -n "${EpisodeSeason}" && -n "${EpisodeNumberRaw}" && "${EpisodeNumberRaw}" =~ ^[0-9]+$ ]]
        then
            EpisodeNumber=$(printf "E%02d" "${EpisodeNumberRaw}")
            SeasonFolder=$(printf "S%02d" "${EpisodeSeason}")

            # Prepare new filename and path
            # Using underscores instead of spaces for the filename as in original script
            CleanSerieName=$(echo "${SerieName}" | sed 's| |_|g')
            NewFileName="${CleanSerieName}_${SeasonFolder}${EpisodeNumber}.${EpisodeExt}"
            NewFilePath="${SerieFolder}/${SeasonFolder}/${NewFileName}"

            if [ ! -f "${NewFilePath}" ]
            then
                SeasonFolderPath=$(dirname "${NewFilePath}")
                if [ ! -d "${SeasonFolderPath}" ]
                then
                    echo "  -> Creating Season folder: ${SeasonFolderPath}"
                    if [ "${DRY_RUN}" = false ]
                    then
                        # Create as film user with appropriate permissions
                        sudo -u film "${MKDIR_PATH}" -m 2775 -p "${SeasonFolderPath}"
                    fi
                fi
                
                if [ "${DRY_RUN}" = false ]
                then
                    echo "  -> Linking: ${NewFilePath} -> ${EpisodePath}"
                    # Set permissions on source so film user can read it
                    chgrp film "${EpisodePath}"
                    chmod g+rw "${EpisodePath}"
                    # Hardlink as film user
                    sudo -u film "${LN_PATH}" "${EpisodePath}" "${NewFilePath}"
                else
                    echo "  -> [DRY-RUN] Would link: ${NewFilePath} -> ${EpisodePath}"
                fi
            fi
        else
            echo "  -> Warning: Could not extract season/episode from: '${EpisodeFile}'"
        fi
    done
done
