#!/bin/bash

# This is a simple script I wrote to convert my entire music library to mp3s for putting on my phone.
# You need to have ffmpeg installed with support for all relevant formats for this to work.

# HOW TO USE:
# Place this script in the directory that your library's root directory is in, i.e. if your music
# library is in ~/Music/Library, this script should be located at ~/Music/dirtomp3.sh
# Set the variable "root" to the name of your library's root directory
# Set "newroot" to the desired root directory of the output. This will be created if it doesn't exist.
# The script should take care of the rest.

root="Library"
newroot="Library_mp3"
mvcount=0
tdcount=$(($(find "$root" -type f -not -path '*/.*' | wc -l)))

printf "\x1b[s"
echo ".00% done ($mvcount/$tdcount files processed)"

recurse() {
    path="$1"
    for f in "$path/"*; do
        nf=$(echo "$f" | sed "s/^$root/$newroot/;s/\.flac\|\.wav\|\.ogg$/.mp3/")
        if [[ "$f" != $root* ]]; then
            echo "Script attempted to access item $f outside designated operating area, aborting"
            exit
        fi
        if [[ "$nf" != $newroot* ]]; then
            echo "Script attempted to access item $nf outside designated operating area, aborting"
            exit
        fi
        if [[ -d "$f" ]]; then
            mkdir -p "$nf"
            recurse "$f"
        elif [[ -f $f ]]; then
            printf "\x1b[2K%s" "$(echo "$f" | head -c $(tput cols))"
            if [[ "$f" == *.flac ]] || [[ "$f" == *.wav ]] || [[ "$f" == *.ogg ]]; then
                if [[ ! -f $nf ]] || [[ $f -nt $nf ]]; then
                    ffmpeg -i "$f" "$nf" -loglevel 0
                    if [[ $? -gt 0 ]]; then
                        exit
                    fi
                fi
            elif [[ "$f" == *.mp3 ]]; then
                cp -u "$f" "$nf"
            elif [[ "$f" == *.png ]] || [[ "$f" == *.jpg ]] || [[ "$f" == *.jxl ]] || [[ "$f" == *.gif ]]; then
                cp -u "$f" "$nf"
            fi
            mvcount=$((mvcount+1))
            printf "\x1b[u%s%% done (%d/%g files processed)\n" "$(echo "scale=2; $(echo "$mvcount/$tdcount*100" | bc -l)/1" | bc)" "$mvcount" "$tdcount"
         fi
    done
}

mkdir -p $newroot
recurse "$root"
printf "\x1b[2K"
