#!/bin/bash
#
# This script copies the core Bela files to the BeagleBone Black
# in preparation for building projects. It will remove any existing
# Bela directory before copying the files over

[ -z "$BBB_ADDRESS" ] && BBB_ADDRESS="root@192.168.7.2"
[ -z "$BBB_BELA_HOME" ] && BBB_BELA_HOME="~/Bela/"
function usage
{
    THIS_SCRIPT=`basename "$0"`
    echo "Usage: $THIS_SCRIPT [-b path-on-beaglebone]"

    echo "
    This script copies the core Bela files to the BeagleBone, REMOVING
    any previous files found at that location. This should be done before
    running any of the other build scripts in this directory. The -b option
    changes the default path, which is otherwise $BBB_BELA_HOME."
}

OPTIND=1

while getopts "b:h" opt; do
    case $opt in
        b)            BBB_BELA_HOME=$OPTARG
                      ;;
        h|\?)         usage
                      exit 1
    esac
done

echo "Copying Bela core files to $BBB_BELA_HOME"

shift $((OPTIND-1))

# Find location of this script so we can locate the rest of the files
SCRIPTPATH=$(readlink "$0")
SCRIPTDIR=$(dirname "$SCRIPTPATH")
[ -z "$IDE_FOLDER" ] && IDE_FOLDER=$SCRIPTDIR/../../bela-ide/

read -p "Warning: this script will DELETE any existing Bela files from your BeagleBone! Continue? (y/N) " -r
echo
if [[ $REPLY = [yY]  ]]
then
# Stop Bela if running and remove all files
  echo "Stopping Bela and removing old files." 
  ssh $BBB_ADDRESS "screen -X -S Bela quit &>/dev/null; pkill Bela; sleep 0.5 ; rm -rf $BBB_BELA_HOME ; mkdir $BBB_BELA_HOME"

# Copy relevant files to BeagleBone Black
  echo "Copying new files to BeagleBone..."
  scp -q -r $SCRIPTDIR/../core $SCRIPTDIR/../include $SCRIPTDIR/../Makefile $SCRIPTDIR/../libNE10.a $SCRIPTDIR/../libprussdrv.a $SCRIPTDIR/../examples $BBB_ADDRESS:$BBB_BELA_HOME &&\
  scp -q $SCRIPTDIR/../libpd.so $BBB_ADDRESS:/usr/lib
  if [ $? -ne 0 ]
  then 
	  echo "Error while copying files"
	  exit
  fi
# Create remaining directories needed for building
  echo "Creating directory structure on BeagleBone..."
  ssh $BBB_ADDRESS "mkdir -p $BBB_BELA_HOME/build ; mkdir -p $BBB_BELA_HOME/build/core ; mkdir -p $BBB_BELA_HOME/build/projects; mkdir -p $BBB_BELA_HOME/projects" &&\
  echo "Done."
else
  echo "Aborting..."
  exit
fi

#-------------
#Installing IDE
stat $IDE_FOLDER/scripts/setup_IDE.sh > /dev/null
if [ $? -eq 0 ]
then
  cd $IDE_FOLDER/scripts;
  ./setup_IDE.sh
else
  echo "No IDE found, no IDE installed. You can get a copy of the IDE files from https://github.com/LBDonovan/bela-ide"
fi;
