#!/bin/sh
#
# This script compiles a Bela 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_LIBPD_EXECUTABLE_PATH="~/libpd/Bela"
BBB_LIBPD_PROJECT_PATH="~/libpd/source/"
RUN_PROJECT=1
COMMAND_ARGS=
RUN_IN_FOREGROUND=0
RUN_WITHOUT_SCREEN=0

usage()
{
	THIS_SCRIPT=`basename "$0"`
	echo "Usage: $THIS_SCRIPT [-c 'command-line-args'] [-nfb] <directory-with-source-files>"
	echo "
	This script copies a PureData project to the BeagleBone and runs it 
	using libpd. The Bela-libpd executable should have first been copied
	to the $BBB_LIBPD_EXECUTABLE_PATH folder on the Beaglebone.
	The source directory should contain a file called _main.pd, which is the 
	patch that will be loaded into Pd. All the content of the folder is 
	recursively copied and the folder structure is flattened.
	
	If the argument -n is passed, the output will not be run after copying the files.
	
	The -c option passes command-line arguments to the Bela program; 
	enclose the argument string in quotes.
	
	The -b argument runs the projet in the background, so that no output is displayed
	in the terminal.
	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 "bc:nfFh" opt; do
	case $opt in
	c)
		COMMAND_ARGS=$OPTARG
	;;
	b)
		RUN_IN_FOREGROUND=0
	;;
	f)
		RUN_WITHOUT_SCREEN=1
	;;
	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

ADDITIONAL_FOLDER=$1

if [ -z "$ADDITIONAL_FOLDER" ]
then
	usage
	exit
fi

#reconstruct the command line options 
OPT=
[ $RUN_IN_FOREGROUND -eq 0 ] && OPT="$OPT -b"
[ $RUN_WITHOUT_SCREEN -eq 1 ] && OPT="$OPT -f"

./build_project.sh -p libpd -r $ADDITIONAL_FOLDER $OPT -c "$COMMAND_ARGS" ../examples/basic_libpd/
