#!/bin/bash
# genvoice.sh
#
# Copyright 2006 Jonas Häggqvist, some parts Copyright 2004 Daniel Gudlat
#
# Distributed under the terms of the GPL version 2
#
# Bugs
# - Probably full of bashisms

# Include voicecommon.sh from the same dir as this script
# Any settings from voicecommon can be overridden if added below the following
# line.
source `dirname $0`'/voicecommon.sh'

####################
# General settings #
####################

# which TTS engine to use. Available: festival, flite
TTS_ENGINE=festival
# which encoder to use, available: lame, speex, vorbis (only lame will produce
# functional voice clips)
ENCODER=lame
# Where to save temporary files
TEMPDIR=/tmp

###################
# End of settings #
###################

function createvoicefile() {
    $VOICEFONT "$LANG_FILE" "$TEMPDIR/" "./$RLANG-$TARGET.voice"
}

function deletefiles() {
    # XXX: might be unsafe depending on the value of TEMPDIR
    rm -vf "$TEMPDIR"/LANG_*
    rm -vf "$TEMPDIR"/VOICE_*
}

function generateclips() {
    ROCKBOX_DIR="$1"
    RLANG="$2"
    TARGET="$3"
    GENLANG="$ROCKBOX_DIR"/tools/genlang
    ENGLISH="$ROCKBOX_DIR"/apps/lang/english.lang
    LANG_FILE="$ROCKBOX_DIR"/apps/lang/$RLANG.lang

    echo "Notice: Generating $RLANG for $TARGET"

    $GENLANG -e=$ENGLISH -o -t=$TARGET $LANG_FILE |(
    i=0
    while read line; do
        case $[ $i % 3 ] in
            0)
                # String ID no.
                NUMBER=`echo $line |cut -b 2-`
                ;;
            1)
                # String ID
                ID=`echo $line |cut -b 5-`
                ;;
            2)
                # String
                STRING=`echo $line |cut -b 8-`

                # Now generate the file
                speak "$STRING" "$TEMPDIR/$ID".wav
                encode "$TEMPDIR/$ID".wav "$TEMPDIR/$ID".mp3
                ;;
        esac
        i=`expr $i + 1`
    done
    )
}

if [ -z "$3" ]; then
    echo "Usage: $0 rockboxdirectory language target";
    exit 32
else
    if [ ! -d "$1" ] || [ ! -f "$1/tools/genlang" ]; then
        echo "Error: $1 is not a Rockbox directory"
        exit 33
    fi
    if [ ! -f "$1/apps/lang/$2.lang" ]; then
        echo "Error: $2 is not a valid language"
        exit 34
    fi
    # XXX: check for valid $TARGET?
fi

VOICEFONT=`dirname $0`/voicefont
if [ ! -x $VOICEFONT ]; then
    echo "Error: $VOICEFONT does not exist or is not executable"
    exit 35
fi

init_tts
init_encoder
generateclips "$1" "$2" "$3"
stop_tts
createvoicefile
deletefiles
