#!/bin/bash
#
# mkmp3.sh v1.0, 2017/05/21 ed <irc.rizon.net>
#
# takes all the flacs below your current directory
# and converts them to ../foldername [V0]/theflacpath.mp3
#
###############################################################

# where to save the converted files
outdir=mp3v0

# on second thought, ../foldername [V0]/
dir="$(pwd)"
dir="${dir##*/}"
outdir="$(
	printf '../%s\n' "$dir" |
	sed -r 's/\[FLAC\]$/[V0]/'
)"
[[ -e "$outdir" ]] &&
	outdir="$outdir [V0]"

# make sure we're not causing a mess
[[ -e "$outdir" ]] &&
{
	echo output directory exists
	exit 0
}

# temp file for flac file list
qfn="$(mktemp)"

# find all flacs
find -type f -iname \*.flac |
sort > "$qfn"

# number of files to process
n=0
nfiles="$(
	cat "$qfn" |
	wc -l
)"

# for each flac
while IFS= read -r line
do
	n=$((n+1))
	dir="${line%/*}"
	fn="${line##*/}"
	mp3fn="${fn%.*}.mp3"
	
	# if we have tput, designate a line on top of the screen as status bar
	which tput > /dev/null &&
	{
		height=$(tput lines)
		printf '\033[s\033[r\033[H\033[7m[[ Processing file %s of %s : %s ]]\033[7m\033[K\n\033[2;%sr\033[u' \
			$n $nfiles "$line" $height
	}
	
	mkdir -p "$outdir/$dir/"

	# convert to mp3 without any file attachments
	ffmpeg -i "$line" -map 0:a -q:a 0 "$outdir/$dir/$mp3fn" < /dev/null ||
		break
done < <(
	cat "$qfn"
)

# reset terminal scroll region
printf '\033[s\033[r\033[u\n'
rm "$qfn"

