#!/bin/bash
#
# This script runs an already-compiled BeagleRT project on the
# BeagleBone Black.

[ -z "$BBB_ADDRESS" ] && BBB_ADDRESS="root@192.168.7.2"
[ -z "$BBB_BELA_HOME" ] && BBB_BELA_HOME="~/BeagleRT/"
[ -z "$BBB_SCREEN_NAME" ] && BBB_SCREEN_NAME="BeagleRT"
[ -z "$RUN_PROJECT" ] && RUN_PROJECT=1
[ -z "$COMMAND_ARGS" ] && COMMAND_ARGS=
[ -z "$RUN_IN_FOREGROUND" ] && RUN_IN_FOREGROUND=1
[ -z "$RUN_WITHOUT_SCREEN" ] && RUN_WITHOUT_SCREEN=0
[ -z "$BBB_PROJECT_HOME" ] && BBB_PROJECT_HOME="${BBB_BELA_HOME}/projects/"
[ -z "$BBB_DEFAULT_PROJECT_NAME" ] && BBB_DEFAULT_PROJECT_NAME="scriptUploadedProject"

function usage
{
    THIS_SCRIPT=`basename "$0"`
    echo "Usage: $THIS_SCRIPT [-b path-on-beaglebone] [-c command-line-args] [-fF]"

    echo "
    This script runs a previously compiled BeagleRT project on the 
    BeagleBone Black. The -b option changes the default path, which
    is otherwise $BBB_BELA_HOME. The -c option passes command-line arguments
    to the BeagleRT program; enclose the argument string in quotes.
	
    The -f argument runs the project in the foreground of the current terminal,
    within a screen session that can be detached later. The -F argument runs
	the project in the foreground of the current terminal, without screen, so
	the output can be piped to another destination."
}

OPTIND=1

while getopts "b:c:fFh" opt; do
    case $opt in
        b)            BBB_BELA_HOME=$OPTARG
                      ;;
        c)            COMMAND_ARGS=$OPTARG
                      ;;
        f)            RUN_IN_FOREGROUND=1
                      ;;
	F)            RUN_WITHOUT_SCREEN=1
		              ;;
        h|\?)         usage
                      exit 1
    esac
done

if [ -z "$1" ]
then
    BBB_PROJECT_NAME=$BBB_DEFAULT_PROJECT_NAME
else
    BBB_PROJECT_NAME=$1
fi

shift $((OPTIND-1))

MAKE_COMMAND="make stop -C $BBB_BELA_HOME PROJECT='$BBB_PROJECT_NAME' CL='$COMMAND_ARGS'"
echo "Running $BBB_PROJECT_NAME..."
if [ $RUN_WITHOUT_SCREEN -ne 0 ]
then
    ssh -t $BBB_ADDRESS "$MAKE_COMMAND run"
elif [ $RUN_IN_FOREGROUND -eq 0 ]
then
    ssh $BBB_ADDRESS "$MAKE_COMMAND runscreenfg"
else
    ssh -t $BBB_ADDRESS "$MAKE_COMMAND runscreen"
fi
