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

cd "$1" 2>/dev/null || true

# where to save the converted files
outdir=ogg

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

# 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
cat "$qfn" |
while read line
do
	n=$((n+1))
	dir="${line%/*}"
	fn="${line##*/}"
	oggfn="${fn%.*}.ogg"
	
	# 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[27m\033[K\n\033[2;%sr\033[u' \
			$n $nfiles "$line" $height
	}
	
	mkdir -p "$outdir/$dir/"

	# convert to ogg without any file attachments
	LD_LIBRARY_PATH=/home/ed/pe/aotuv/lib:"$LD_LIBRARY_PATH" \
	ffmpeg -i "$line" -map 0:a -acodec libvorbis -q:a 5 "$outdir/$dir/$oggfn" < /dev/null ||
		break
done

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

