#!/bin/sh
# Filename:      a2mp3
# Purpose:       Program to optimize various music formats to mp3 for mp3-players
# Authors:       (c) Michael Gebetsroither <michael.geb@gmx.at>
# License:       This file is licensed under the GPL v2.
# Latest change: Sat Dec 24 15:04:59 CET 2005
################################################################################


###
### __INCLUDES
###
. /etc/grml/sh-lib
#. /etc/grml/sysexits-sh



###
### __VARIABLES
###

verbose_=0
USER_="`id -un`"
CONF_FILE_='/etc/a2mp3.conf'
UCONF_FILE_="/home/${USER_}/.a2mp3.conf"

OUT_DIR_="/home/${USER_}/mp3tmp"   # output directory for encoded mp3 files
TMP_=""     # tmpfile
MP3_='lame'
MP3_OPTS_='-h -V7 --quiet'

test -r "$CONF_FILE_" && . "$CONF_FILE_"
test -r "$UCONF_FILE_" && . "$UCONF_FILE_"


###
### __FUNCTIONS
###

printUsage()
{
  cat <<EOT
Usage: "$PROG_NAME__" [OPTIONS] <audio file> <audio file> ...

$PROG_NAME__ is a program to convert anyhing to mp3
This Program converts all files given at commandline to your personal folder:
    - $OUT_DIR_

OPTIONS:
   -d         output directory (default=~/mp3tmp)
   -v         verbose (show what is going on, v++)
   -h         this help text

EOT
}


getThingsFromCmd()
{ 
    local num=1;
    while [ $# != 0 ]; do
        case "$1" in            # Do not prozess
            "") continue ;;     #   an empty IP
            \#*) continue ;;    #   a comment
        esac
        dprint "$num: $1"
        num=$(($num+1))
        echo "$1" >> "$TMP_"
        shift
    done
}


removeTmpFiles()
{
    rm -rf $TMP_
}


getOutFile()
{
    local file_name_="$1"   # file name + (path) of mp3 (not known)
    local ext_="$2"         # filetype extension
    
    local name_="${file_name_##/*/}"    # stripp off path
    dprint "getOutFile(): name=\"$name_\""
    name_="${name_%.*}"                 # stripp off extension
    dprint "getOutFile(): name=\"$name_\""
    local file_="$OUT_DIR_/$name_" # name + output path

    file_="`echo \"$file_\" |tr ' ' '_'`"
    local a_="$file_"
    local num_="1"
    while [ -e "${a_}.$ext_" ]; do
        a_="${file_}_$num_"
        num_=$(($num_+1))
    done
    a_="${a_}.$ext_"
    touch "$a_"
    dprint "getOutFile(): filename=\"$a_\""
    echo "$a_"
}


# encoder functions for different input audioformats {{{
encodeMp3File()
{
    local infile_="$1"
    local outfile_="`getOutFile \"$1\" mp3`"

    local tmp_=''
    local tag_=''
    local artist_=''
    local album_=''
    local title_=''

    dprint "encodeMp3File(): outfile=$outfile_"

    tag_="`mp3info -p 'artist:%a\nalbum:%l\ntitle:%t\n' \"$infile_\"`"
    tmp_="`echo \"$tag_\" |grep artist:`"; artist_="${tmp_#*:}"
    tmp_="`echo \"$tag_\" |grep album:`"; album_="${tmp_#*:}"
    tmp_="`echo \"$tag_\" |grep title:`"; title_="${tmp_#*:}"

    echo "$infile_ => ${outfile_##/*/}"
    execute "$MP3_ $MP3_OPTS_ --tt \"$title_\" --ta \"$artist_\" --tl \"$album_\" \"$infile_\" \"$outfile_\"" eprint >/dev/null
    if [ $? != 0 ]; then
        warn "Problems encoding file \"$infile_\" with lame"
        rm "$outfile_"
    fi
}

encodeOggFile()
{
    local infile_="$1"
    local outfile_="`getOutFile \"$1\" mp3`"

    local tmp_=''
    local tag_=''
    local artist_=''
    local album_=''
    local title_=''

    dprint "encodeOggFile(): outfile=$outfile_"

    tag_="`ogginfo \"$infile_\"`"
    tmp_="`echo \"$tag_\" |grep \"ARTIST=\"`"; artist_="${tmp_#*=}"
    tmp_="`echo \"$tag_\" |grep \"ALBUM=\"`"; album_="${tmp_#*=}"
    tmp_="`echo \"$tag_\" |grep \"TITLE=\"`"; title_="${tmp_#*=}"
    
    echo "$infile_ => ${outfile_##/*/}"
    oggdec -Q -b 16 -o - "$infile_" |$MP3_ $MP3_OPTS_ --tt "$title_" --ta "$artist_" --tl "$album_" - "$outfile_" >/dev/null
    if [ $? != 0 ]; then
        warn "Problems encoding file \"$infile_\""
        eprint "oggdec -Q -b 16 -o - \"$infile_\" |$MP3_ $MP3_OPTS_ --tt \"$title_\" --ta \"$artist_\" --tl \"$album_\" - \"$outfile_\""
        rm "$outfile_"
    fi
}
# }}}


encodeFiles()
{
    local file_=''      # filename
    local type_=''      # type of file

    cat "$TMP_" | while read file_; do
        type_="${file_##*.}"
        case $type_ in
            mp3) encodeMp3File "$file_" ;;
            ogg) encodeOggFile "$file_" ;;
            oga) encodeOggFile "$file_" ;;
            *)  warn "file has no extension, skipping" ;;
            ?)  warn "unknown extension \"$type_\"" ;;
        esac
    done
}



###
### __MAIN
###

while getopts "d:hv" opt; do
    case "$opt" in
        d) OUT_DIR_="${OPTARG:-$OUT_DIR_}" ;;
        h) printUsage; exit ;;
        v) verbose_=$(($verbose_+1)); setVerbose $verbose_ ;;
        ?) printUsage; exit 64 ;;
    esac
done
shift $(($OPTIND - 1))  # set ARGV to the first not parsed commandline parameter

disableSyslog

TMP_=`mktemp -t a2mp3-XXXXXX || die 'could not create tmp file' $?`
setExitFunction 'removeTmpFiles'

test -e "$OUT_DIR_" || mkdir "$OUT_DIR_"

getThingsFromCmd "$@"

encodeFiles

removeTmpFiles
exit 0

# END OF FILE
################################################################################
# vim:foldmethod=marker
