#!/bin/bash

#   Audina Audiobook MP3 Converter
#   Copyright (C) Bohdan R. Rau 2012 <ethanak@polip.com>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write see:
#               <http://www.gnu.org/licenses/>.

function helpme()
{
(
echo "Sposob użycia: $0 [opcje] <outputdir>"
echo "Opcje:"
echo "-x <ext> - przy skanowaniu katalogu zostanie uzyte"
echo "           rozszerzenie \"<ext>\" zamiast \"mp3\""
echo "Opcje -s, -d, -m, -g, -p, -E, -B, -G, -r, -i oraz -P"
echo "będą przekazane do programu audina"

echo "Program musi być uruchomiony w katalogu zawierającym pliki mp3"
echo "Utworzony zostanie katalog <outputdir> zawierający przetworzone pliki") | \
if [ "`locale charmap`" = "UTF-8" ] ; then
    cat
else
    iconv -f UTF-8 -t `locale charmap`//TRANSLIT
fi
exit 1
}

austr="-S"
multipart=f
exten="mp3"
while getopts "hs:d:m:p:g:E:P:B:G:r:i:x:" opt ; do
    if [ "$opt" == "h" ] ; then
        helpme
    elif [ "$opt" == "x" ] ; then
        exten="$OPTARG"
    elif [ "$opt" == "s" ] || [ "$opt" == "d" ] || \
        [ "$opt" == "g" ] || \
        [ "$opt" == "E" ] || \
        [ "$opt" == "B" ] || \
        [ "$opt" == "P" ] || \
        [ "$opt" == "i" ] || \
        [ "$opt" == "G" ] || \
        [ "$opt" == "m" ] || [ "$opt" == "p" ] ; then
        austr=$austr" -$opt $OPTARG"
    elif [ "$opt" == "r" ] ; then
        austr=$austr" -$opt $OPTARG"
        multipart=t
    else
        echo "Unknown option "$opt
        helpme
    fi
done

shift $((OPTIND-1))

if [ $# -lt 1 ]; then
	helpme
fi

dir="$1"
echo "Converting"

mkdir -p "$dir"
count=`find . -maxdepth 1 -iname "*.$exten"| wc -l`
ls *.$exten | sort | while read i; do
    current=$(($current+1))
	out=$dir'_'`printf "%03d" ${current}`.mp3
	echo "[$current/$count] $out"
	audina $austr "$i" "$dir/$out" #2>/dev/null
done
