#!/bin/bash
#
# This script compiles a BeagleRT project on the BeagleBone Black and
# optionally runs it. Pass a directory path in the first argument. 
# The source files in this directory are copied to the board and compiled.

BBB_ADDRESS="root@192.168.7.2"
BBB_PATH="~/BeagleRT"
RUN_PROJECT=1
COMMAND_ARGS=

function usage
{
    THIS_SCRIPT=`basename "$0"`
    echo "Usage: $THIS_SCRIPT [-b path-on-beaglebone] [-c command-line-args] [-n] <directory-with-source-files>"
    echo "
    This script copies a directory of source files to the BeagleBone, compiles
    and runs it. The BeagleRT core files should have first been copied over
    using the setup_board.sh script supplied with BeagleRT.

    The source directory should contain at least one .c, .cpp or .S file.
    If the argument -n is passed, the output will not be run after compiling.
    The argument -b will change the local path on the BeagleBone where the
    BeagleRT files are found. The -c option passes command-line arguments to
    the BeagleRT program; enclose the argument string in quotes."
}

OPTIND=1

while getopts "b:c:nh" opt; do
    case $opt in
        b)            BBB_PATH=$OPTARG
                      ;;
        c)            COMMAND_ARGS=$OPTARG
                      ;;
        n)    	      RUN_PROJECT=0
                      ;;
        h|\?)         usage
                      exit 1
    esac
done

shift $((OPTIND-1))

# Check that we have a directory containing at least one source file
# as an argument
if [ -z "$1" ]
then
    usage
    exit
fi

C_FILES=$(find "$1" -maxdepth 1 -type f -name "*.c")
CPP_FILES=$(find "$1" -maxdepth 1 -type f -name "*.cpp")
ASM_FILES=$(find "$1" -maxdepth 1 -type f -name "*.S")

if [[ -z $C_FILES ]] && [[ -z $CPP_FILES ]] && [[ -z $ASM_FILES ]]
then
    echo "Please provide a directory containing .c, .cpp or .S files."
#    echo "Usage: $THIS_SCRIPT [directory-with-source-files]"
    usage
    exit
fi

# Stop BeagleRT and clean out old source files
echo "Stopping BeagleRT and removing old source files..."
ssh -t -t $BBB_ADDRESS "kill -s 2 \`pidof BeagleRT\` 2>/dev/null; sleep 0.5; make sourceclean -C $BBB_PATH"

# Copy new source files to the board
echo "Copying new source files to BeagleBone..."
scp "$1"/* "$BBB_ADDRESS:$BBB_PATH/source/"

# Make new BeagleRT executable and run
if [ $RUN_PROJECT -eq 0 ]
then
    echo "Building project..."
    ssh $BBB_ADDRESS "make all -C $BBB_PATH"
else
    echo "Building and running project..."
    ssh $BBB_ADDRESS "make all -C $BBB_PATH ; screen -d -m $BBB_PATH/BeagleRT $COMMAND_ARGS"
fi