#!/bin/bash

# shell script for automatic uploading/compiling of pd patch onto bbb
# Christian Heinrichs 2015
#
# example usage: sh upload-and-compile.sh -f bwg-tests -q -e

trap "{ echo "";exit 0; }" SIGINT SIGTERM

workingdir=".."
verbose="0"
render="0"
pdpath=""
NO_UPLOAD="0"
WATCH="0"
FORCE="0"
#make sure the paths have the trailing / . 
projectpath="../projects/heavy/hvtemp/"
[ -z "$BBB_ADDRESS" ] && BBB_ADDRESS="root@192.168.7.2"
[ -z "$BBB_BELA_HOME" ] && BBB_BELA_HOME="~/Bela/"
[ -z "$BBB_PROJECT_HOME" ] && BBB_PROJECT_HOME="${BBB_BELA_HOME}/projects/"
BBB_DEFAULT_PROJECT_NAME="heavyProject"
[ -z "$BBB_PROJECT_NAME" ] && BBB_PROJECT_NAME=$BBB_DEFAULT_PROJECT_NAME
COMMAND_ARGS=
RUN_PROJECT=1
RUN_IN_FOREGROUND=0
RUN_WITHOUT_SCREEN=1
BELA_PYTHON27=

if [ -z "$BELA_PYTHON27" ]; then
    for PY in python python2.7 ; do
        python --version 2>&1 | grep "2\.7" &> /dev/null
        if [ $? -eq 0 ]; then
            BELA_PYTHON27=$PY
            break;
        fi;
    done;
fi;

if [ -z "$BELA_PYTHON27" ]; then
    echo "It looks like you might not have python2.7 installed. If you do, please specify the path
    to your python2.7 executable in the environmental variable \$BELA_PYTHON27"
    exit 1;
fi;


function usage
{
printf "\nUSAGE: build_pd.sh [[-i input folder containing _main.pd file ]\
 [-o output folder for new heavy project .c files (default ../projects/heavy/hvtemp)]\
 [-b bbb path to copy to (default ~/Bela)] | [-h] | [-w|--watch] | [-n|--noupload] | [-r|--release arg]\n"
printf "\nexample: build_pd.sh -i ../projects/heavy/pd/hello-world -o ../projects/heavy/hello-world\n"
echo "If --watch is selected, the script will check every 1s for any file that is modified in the source folder, which triggers\
the building process and runs the process.
If --screen is selected, the prompt returns to the user after launching Bela in a screen on the target device.
If --screen and --watch are combined, while the process is running in the screen, modifications to the source files will \
still trigger a new build.
-r allows to build against a specific Heavy release. Default is the most recent version.
"
}

while [ "$1" != "" ]; do
    case $1 in
        -b | --bbb )            shift
                                BBB_BELA_HOME=$1
                                ;;
        -i | --input )          shift
                                pdpath=$1
                                ;;
        -o | --output )         shift
                                projectpath=$1
                                ;;
        -r | --release )        shift
                                release=$1
                                ;;
        -v | --verbose )        verbose=1
                                ;;
        -r | --render )         shift
                                render=1
                                ;;
        -s | --screen )         RUN_WITHOUT_SCREEN="0"
                                ;;
        -w | --watch )          WATCH=1
                                ;;
        -n | --noupload )      NO_UPLOAD=1
                                ;;
        -h | --help )           usage
                                exit
                                ;;
        * )                     usage
                                exit 1
    esac
    shift
done

if [ -z $release ]
then 
  RELEASE_STRING=
else 
  RELEASE_STRING="-r $release"
fi

function uploadBuildRun(){
    if [ $NO_UPLOAD -eq 0 ]; then
        # remove old static files to avoid obsolete errors
        # use -rf to prevent warnings in case they do not exist
        rm -rf "$projectpath"/Hv* "$projectpath"/Message* "$projectpath"/Control* "$projectpath"/Signal* &>/dev/null

        # invoke the online compiler
        "$BELA_PYTHON27" hvresources/uploader.py "$pdpath"/ -n bbb -g c -o "$projectpath" $RELEASE_STRING;
        if [ $? -ne 0 ]; then
        #echo "ERROR: an error occurred while executing the uploader.py script"
        echo "error"
        exit 1
        fi;
    fi;

    echo "";
    #echo "*|*|* Successfully uploaded and converted pd patch into super-fast optimized C code. Brought to you by Heavy! *|*|*";
    echo "";

    BBB_PROJECT_FOLDER=$BBB_PROJECT_HOME"/"$BBB_PROJECT_NAME #make sure there is no trailing slash here
    BBB_NETWORK_TARGET_FOLDER=$BBB_ADDRESS:$BBB_PROJECT_FOLDER

    # check how to copy/sync render.cpp file...
    # don't replace render.cpp file if custom one provided in output folder
    if [ -f $projectpath"/render.cpp" ]; then
        echo "Found custom render.cpp file in output folder";
        ssh -t $BBB_ADDRESS "rm ${BBB_PROJECT_FOLDER}/build/render.*" 
    else
        if [ $render -eq 0 ]; then
        cp "hvresources/render.cpp" $projectpath/;
        fi;
    fi;

    cp "hvresources/HvUtils.h" $projectpath/;

    echo "updating files on board..."

    rsync -c -rv --exclude 'HvContext*' "$projectpath"/ "$BBB_NETWORK_TARGET_FOLDER";
    if [ $NO_UPLOAD -eq 0 ]; then
        # for whatever reason these big files used to hang when transferring with rsync
        scp "$projectpath"/HvContext* $BBB_NETWORK_TARGET_FOLDER
    fi;

    if [ $? -ne 0 ]; then
    echo "";
    echo ":( :( :( ERROR: while synchronizing files with the BBB. Is the board connected and the correct SD card inserted? :( :( :(";
    echo "";
    exit 1;
    fi;
    # exit
    #produce a list of files which content has changed (not just the date)
    #TODO: could be made faster (perhaps) by backing up the folder locally instead of bbb
    # UPDATED_FILES=`rsync -naic --log-format="%f" "$projectpath" "$BBB_BELA_HOME"/source | grep -v "\.$"`
    # echo "UPDATEDFILES : $UPDATED_FILES"
    # exit 2
    # remove old executable and heavy context .o/.d files
    if [ $NO_UPLOAD -eq 0 ]; then
        ssh $BBB_ADDRESS "rm -rf "$BBB_PROJECT_FOLDER/$BBB_PROJECT_NAME;
    fi;
    SCREEN_NAME=Bela
    # Make new Bela execut/able and run
    # It does not look very nice that we type the same things over and over
    # but that is because each line is an ssh session in its own right
    MAKE_COMMAND="make stop -C $BBB_BELA_HOME PROJECT='$BBB_PROJECT_NAME' CL='$COMMAND_ARGS'"
    if [ $RUN_PROJECT -eq 0 ]
    then
        echo "Building project..."
        ssh $BBB_ADDRESS "$MAKE_COMMAND"
    else
        echo "Building and running project..."
        if [ $RUN_WITHOUT_SCREEN -eq 1 ]
        then
            ssh -t $BBB_ADDRESS "$MAKE_COMMAND run" 
        elif [ $RUN_IN_FOREGROUND -eq 1 ]
        then
            # Run in screen without detaching
            ssh -t $BBB_ADDRESS "$MAKE_COMMAND runscreenfg"
        else
            # Run in screen and detach
            ssh -t $BBB_ADDRESS "$MAKE_COMMAND runscreen"
        fi
    fi
} #uploadBuildRun

uploadBuildRun

if [ $WATCH -ne 0 ]; then
    WAIT_STRING="\rWaiting for changes in $pdpath"
    while true; do
        printf "$WAIT_STRING   "
        sleep 0.3
        printf "$WAIT_STRING.  "
        sleep 0.3
        printf "$WAIT_STRING.. "
        sleep 0.3
        printf "$WAIT_STRING..."
        sleep 0.3
        uploadBuildRun
    done;
fi;
#ssh -t root@192.168.7.2 "kill -s 2 \`pidof heavy_template\` 2>/dev/null; sleep 0.5; rm -f ~/$filename_bbb/Release/source/heavy/HvContext_bbb.? ~/$filename_bbb/Release/heavy_template && make all -C ~/$filename_bbb/Release" &>/dev/null
