#! /bin/sh

#######################################  HOW TO USE  ################################################
#   manually copy script in show folder next to the seasons
#   manually rename the seasons folders like Season_01, Season_02, ..., Season_42
#   manually rename the episodes with PREFIX old_ like old_ShowName_S01_E01 like: for f in * ; do mv -- "$f" "old_$f" ; done
#   run script for testing (uncomment line 28 for conversions)
#   manually delete after completion all files with PREFIX old_
#   find . -name "*.nfo" -exec rm -rf {} \;
#####################################################################################################

PREFIX="old_"
echo "starting script ..."
echo " "
ROOT_DIR=$PWD                                                   # get current directory aka. the show folder
echo "ROOT_DIR: " $ROOT_DIR
for seasons in $ROOT_DIR/**; do
if [[ -d $seasons ]]; then
    echo "Season found: $seasons"
    cd $seasons
    for episodes in ${PREFIX}*; do
    OLD_EPISODE_NAME=$episodes
    NEW_EPISODE_NAME=$"$(b=${episodes##*/}; echo ${b%.*}).mkv"
    NEW_EPISODE_NAME=$"${NEW_EPISODE_NAME//$PREFIX/}"
    
    echo "OLD_EPISODE_NAME: $OLD_EPISODE_NAME"
    echo "NEW_EPISODE_NAME: $NEW_EPISODE_NAME"
    
    if [ -f "$NEW_EPISODE_NAME" ]; then
        echo "$NEW_EPISODE_NAME exists."
    else 
        echo "$NEW_EPISODE_NAME does not exist."
        #ffmpeg -i $OLD_EPISODE_NAME -c:v libaom-av1 -c:a libopus -mapping_family 1 -af aformat=channel_layouts=5.1 -c:s copy -map 0 -crf 24 -b:v 0 -b:a 128k -cpu-used 4 -row-mt 1 -tiles 2x2 $NEW_EPISODE_NAME
    fi
    done
fi
done
