#!/bin/bash
# Updates podcasts, downloads new episodes, then normalizes them.

if [ "$1" = "-h" ]; then
        echo "Updates podcasts, downloads new episodes, then normalizes them."
        echo "podcast.sh"
        exit 0
fi

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

declare -a arr=("blowback" "chapo-patreon" "cumtown")
username=palma
source=/home/palma/podcast
target=/home/palma/palmashare/dir2cast
tempdir=$(mktemp -d)

#Set the working directory to the temporary directory.
cd $tempdir

#Update the podcasts.
sudo -u $username podfox update

#Download new episodes for each podcast.
for podcast in "${arr[@]}"; do
        echo "Checking for updates in $podcast..."
        tempfile=$(mktemp)
        sudo -u $username podfox episodes $podcast > $tempfile
        undownloaded=$(head -3 $tempfile | grep "Not Downloaded" | wc -l)
        sudo -u $username podfox download $podcast --how-many=$undownloaded

        for file in $(find $source/$podcast -iname "*.mp3"); do
                filename=$(basename -- "$file")
                extension="${filename##*.}"
                filename="${filename%.*}"
                normalized="$filename.normalized.mp3"
                foundfile=$(find $target/$podcast -iname "$normalized")
                if [ "$foundfile" != "" ]; then
                        echo "$foundfile already exists."
                else
                        echo "No file found for $filename. Normalizing"
                        /home/$username/normalize.sh "$file" "$tempdir/$normalized"
                        echo "Moving $normalized from $tempdir to $target/$podcast"
                        mv * "$target/$podcast"
                fi
        done
done

#Clean up and reset IFS

echo "Cleaning up..."
IFS=$SAVEIFS

#Done!
echo "Done!"
