#!/bin/bash

ino=${PWD##*/}

if [ ! -d "${ESP8266ARDUINO}/tests/host" ]; then
    echo "\${ESP8266ARDUINO} should point to ESP8266 Arduino core directory"
    exit 1
fi

THISLIB=$(pwd)/../..
MAD=$(ls ${THISLIB}/src/libmad/*.c)
PAGER=${PAGER:-less}

cd ${ESP8266ARDUINO}/tests/host

if [ "$1" = "clean" ]; then
    make clean
    cd ${THISLIB}
    rm -f src/*.o src/libmad/*.o
    exit 0
elif [ "$1" = diff ]; then
    cd ${THISLIB}/examples
    diff -u StreamMP3FromHTTP/StreamMP3FromHTTP.ino ${ino}/${ino}.ino | ${PAGER}
    exit 0
else
    echo ""
    echo "usage:"
    echo "  $0"
    echo "  $0 clean"
    echo "  $0 diff"
    echo "  AUDIO=a VALGRIND=v FORCE32=f $0"
    echo "     a=1 play sound (use padsp, open /dev/dsp)"
    echo "     v=1 run in native mode (FORCE32=0) with valgrind"
    echo "     f=1 run in 32 bits mode (if gcc-multilib is installed)"
    echo "variable ESP8266ARDUINO must point to esp8266 Arduino core directory"
    echo ""
    [ "$1" = "-h" ] && exit 0
    sleep 1
fi

run=""

[ -z "${FORCE32}" ] && FORCE32=0
[ -z "${AUDIO}" ] && AUDIO=1

if [ "${AUDIO}" = 1 ]; then
    run="${run} padsp"
fi

if [ "${VALGRIND}" = 1 ]; then
    FORCE32=0
    run="$run valgrind"
fi

touch ${THISLIB}/examples/${ino}/${ino}.ino # rebuild

eval make FORCE32=${FORCE32} -j \
    USERCSOURCES=\"${MAD}\" \
    USERCXXSOURCES=\"${THISLIB}/src/AudioFileSourceBuffer.cpp ${THISLIB}/src/AudioLogger.cpp ${THISLIB}/src/AudioGeneratorMP3.cpp ${THISLIB}/src/AudioFileSourceICYStream.cpp ${THISLIB}/src/AudioFileSourceHTTPStream.cpp\" \
    USERCFLAGS=\"-I${THISLIB}/src/ -DAUDIO=${AUDIO}\" \
    ${THISLIB}/examples/${ino}/${ino}

set -x

$run ./bin/${ino}/${ino} "$@"
stty sane
