#!/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)

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
    exit 0
else
    echo ""
    echo "usage:"
    echo "  $0"
    echo "  $0 clean"
    echo "  $0 diff"
    echo "  FORCE32=0 $0   (run with valgrind)"
    echo "  FORCE32=1 $0   (run in 32 bits)"
    echo "variable ESP8266ARDUINO must point to esp8266 Arduino core directory"
    echo ""
    [ "$1" = "-h" ] && exit 0
    sleep 1
fi

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

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

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/\" \
    ${THISLIB}/examples/${ino}/${ino}

set -x

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

