#!/bin/bash
#
# ::copy::
# ::maintainer::
#
CMD=`basename $0`
destdir=

usage()
{
	echo "
usage: $CMD [options] dir(s) or file(s) ...

options:
 -d|--dest dir	  set destination dir (now: $destdir)
 -r|--recurse	  find files recursing dirs
 -f|--overwrite	  overwrite existing files
 -c|--continue	  ignore errors
 -b bitrate	  set bitrate (now: $bitrate)
" >&2
	exit 1
}


do_extract()
{
	local file="$1"
	local out=`echo "$destdir$1" | sed -e 's#\./##' -e 's/\.[a-z0-9][a-z0-9]*$//'`.mp3
	local stat=
	local dir=`dirname "$out"`
	local action="conv"

	umask 0	# damn ...

	[ -f "$out" ] && {
		action="repl"
		$f_overwrite || return 0
		rm -f "$out"
	}

	[ -d "$dir" ] || {
		mkdir -p "$dir" || return $?
	}

	case "$file" in
	 *.flv|*.mp4|*.avi) ;;	# video sources
	 *.wma|*.aac|*.wav) ;;	# audio sources
	 *)	echo "ignore unknown file: $file" >&2
	 	return 0
		;;
	esac

	trap "cleanup ; rm -f \"$out\"; exit 1" 1 2 3

	echo -n "  $action '$out' ... "
	avconv -i "$file" -vn -b $bitrate -ac 2 -ar 44100 "$out" >log.tmp 2>&1 </dev/null || {
		stat=$?
		rm -f "$out"
		cat log.tmp
		return $stat
	}
	echo -n "(norm) ... "
	normalize-audio "$out" >log.tmp 2>&1 || {
		stat=$?
		rm -f "$out"
		cat log.tmp
		return $stat
	}
	chmod a+r "$out"
	touch --reference "$file" "$out"
	echo "ok"
	return 0
}

cleanup()
{
	rm -f log.tmp
}


# (MAIN)

parms=
f_recurse="false"
f_overwrite="false"
f_continue="false"
stat=0
bitrate="192k"

[ -f .${CMD}-destdir ] && destdir=`cat .${CMD}-destdir`

while [ $# != 0 ]
do
  case $1 in
    -d|--dest)
    	shift
    	[ $# == 0 ] && usage
	destdir="$1"
	;;
    -r|--recurse)
    	f_recurse="true"
	;;
    -f|--overwrite)
    	f_overwrite="true"
	;;
    -c|--continue)
    	f_continue="true"
	;;
    -b)
    	shift
	case $1 in
	  [0-9][0-9]k|[0-9][0-9][0-9]k) bitrate="$1" ;;
	  [0-9][0-9]|[0-9][0-9][0-9]) bitrate="${1}k" ;;
	  *)	echo "bitrate must be a valid number, w/optional trailing 'k' (eg: 128, 192k)" >&2
	 	usage
		;;
	esac
	;;
    -*)	usage
   	;;
    *)
	echo "$1" | grep -q "^/" && {
		echo "absolute path not allowed: '$1'" >&2
		exit 1
	}
    	parms="$parms\n$1"
    	;;
  esac
  shift
done

[ "$parms" == "" ] && usage


# sanity checks
#
destdir=${destdir:-"."}

[ -d "$destdir/." -a -w "$destdir/." ] || {
	echo "destination dir '$destdir' not exists or not writeable" >&2
	exit 1
}

if [ "$destdir" == "." -o "$destdir" == "" ]
then
	destdir=
else
	destdir="$destdir/"
fi

echo -e "$parms" | while read arg
do
	[ "$arg" == "" ] && continue

	if [ -f "$arg" ]
	then
		do_extract "$arg" || {
			$f_continue || {
				cleanup
				exit 1
			}
		}
	else
		if $f_recurse
		then
			find "$arg" -type f | while read file
			do
				do_extract "$file" || {
					$f_continue || {
						cleanup
						exit 1
					}
				}
			done
		else
			ls "$arg" | while read file
			do
				[ -f "$arg/$file" ] && {
					do_extract "$arg/$file" || {
						$f_continue || {
							cleanup
							exit 1
						}
					}
				}
			done
		fi
	fi
done

cleanup
exit $stat
