#!/bin/bash

# Configuration for Orion O6
SYNC_FOLDER="/home/seedbox-sync/"
SYNC_TMP_DOWNLOAD_FOLDER="${SYNC_FOLDER}Downloads"
SERIES_FOLDER="/home/film/Series/"
REQUIRED_USER="film"
LOCK_FILE="/tmp/orion-sort-series.lock"
DRY_RUN=false

# 1. User check
if [ "$(whoami)" != "$REQUIRED_USER" ]; then
    echo "❌ ERROR: This script must be run as '$REQUIRED_USER'."
    exit 1
fi

# 2. Concurrency Lock
if [ -f "$LOCK_FILE" ]; then
    echo "⚠️  Series sorting already in progress. Skipping."
    exit 0
fi
trap 'rm -f "$LOCK_FILE"' EXIT
touch "$LOCK_FILE"

# 3. Change to a neutral directory
cd /

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

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

if [ ! -d "${SERIES_FOLDER}" ]; then
    echo "⚠️  Series folder missing. Skipping."
    exit 0
fi

find "${SERIES_FOLDER}" -maxdepth 1 -mindepth 1 -type d -print0 |
while IFS= read -r -d '' SerieFolder
do
    SerieName=$(basename "${SerieFolder}")
    SearchPattern=$(echo "${SerieName}" | sed 's/ /\.\?/g')
    
    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
        # Optimization: If file already has hardlinks > 1, check if it's already in the Series tree
        HL_COUNT=$(stat -c %h "$EpisodePath")
        
        EpisodeFile=$(basename "${EpisodePath}")
        EpisodeExt=${EpisodeFile##*.}
        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}")
            CleanSerieName=$(echo "${SerieName}" | sed 's| |_|g')
            NewFileName="${CleanSerieName}_${SeasonFolder}${EpisodeNumber}.${EpisodeExt}"
            NewFilePath="${SerieFolder}/${SeasonFolder}/${NewFileName}"

            # If it already exists in the correct spot, skip
            if [ -f "${NewFilePath}" ]; then
                continue
            fi

            # If it has more than 1 hardlink but is NOT at NewFilePath, 
            # it means it's linked elsewhere (Fresh, or another Series folder).
            # We only skip if it's already linked somewhere else to avoid duplicates.
            if [ "$HL_COUNT" -gt 1 ]; then
                echo "  -> Skipping $EpisodeFile (already linked elsewhere)"
                continue
            fi

            SeasonFolderPath=$(dirname "${NewFilePath}")
            if [ ! -d "${SeasonFolderPath}" ]; then
                [ "${DRY_RUN}" = false ] && "${MKDIR_PATH}" -m 2775 -p "${SeasonFolderPath}"
            fi
            [ "${DRY_RUN}" = false ] && "${LN_PATH}" "${EpisodePath}" "${NewFilePath}"
            echo "  -> Linked: ${NewFileName}"
        fi
    done
done
