#! /usr/bin/env nix-shell
#! nix-shell -i bash -p bash fd ripgrep

root=/srv/pool/multimedia/media/Series
while IFS= read -r directory; do
    while IFS= read -r season; do
        season_episodes=()
        while IFS= read -r episode; do
            number="$(basename "$episode" |
                rg --no-config --pcre2 -o "S\d+E\d+" |
                rg --no-config --pcre2 -o "\d+$" |
                awk '$0*=1')"
            season_episodes+=($((number)))
        done < <(fd . "$season" -tf -d1 \
            -E '*.srt' \
            -E '*.jpg' \
            -E '*.nfo' \
            -E '*.nfo-orig' \
            -E '*.json')
        dupe=$(printf '%s\n' "${season_episodes[@]}" | awk '!($0 in seen){seen[$0];next} 1')
        if [[ -z $dupe ]]; then
            continue
        fi
        echo "The episode $dupe is duplicated on $(basename "$season") of $(basename "$directory")"
        echo "$season"
        echo "_______________"
    done < <(fd . "$directory" -td -d1)
done < <(fd . "$root" -td -d 1)
