#!/usr/bin/env bash

#*******************************************************************************
#
# Bare Conductive Text To Speech Utility C++ Example Runner
# ---------------------------------------------------------
#
# run - compiles and runs tts
#
# Written by Stefan Dzisiewski-Smith
#
# This work is licensed under a Creative Commons Attribution-ShareAlike 3.0
# Unported License (CC BY-SA 3.0) http://creativecommons.org/licenses/by-sa/3.0/
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#*******************************************************************************

# make sure we're cd-ed into the script directory
cd "$(dirname "$(readlink -f "${BASH_SOURCE}")")" || exit

# make (& grab the return value)
make --quiet
make_return_value=$?

# put back any of the quotes that BASH removed
# so we can show the user what we're running underneath
execute_and_echo() {
    args=''
    whitespace="[[:space:]]"
    for i in "$@"
    do
        if [[ $i =~ $whitespace ]]
        then
            i=\"$i\"
        fi
        args+="$i ";
    done
    echo "\$ $args"
    bash -c "$args"
}

# only run the code if make succeeded
if [[ $make_return_value -eq 0 ]]; then
    # add sudo if we need to - and pass all arguments to the target
    # the 2>&/dev/null bit redirects stderr to /dev/null so we don't
    # see the error messages that espeak produces - there is a known
    # bug with espeak regarding this
    if [[ $EUID -ne 0 ]]; then
        execute_and_echo sudo ./tts "$@" 2>/dev/null 
    else
        execute_and_echo ./tts "$@" 2>/dev/null 
    fi
fi
