#!/bin/bash

###########################
# Methods
###########################

show_help ()
{
  echo ""
  echo "Syncs your groot workspace with a gopher robot."
  echo ""
  echo "   1) You have installed unison-gtk"
  echo ""
  echo "    Usage:"
  echo "        groot_sync <name>"
  echo "        groot_sync --list"
  echo ""
  echo "    Required Arguments:"
  echo "        <name>      : name of the robot (unison) profile"
  echo ""
  echo "    Options:"
  echo "        --help      : this help message"
  echo "        --list      : list valid robot (unison) profiles."
  echo ""
  exit 0
}

list_profiles()
{
  DIR=/opt/groot/gopher_ws/src/gopher/gopher_meta/resources/unison/
  echo ""
  echo "=============="
  echo "Robot Profiles"
  echo "=============="
  # http://stackoverflow.com/questions/13676108/using-ls-how-can-i-list-files-without-file-extension-the-part-after-the-dot
  
  ls -1 ${DIR} | sed -e 's/\..*$//' | sed 's/^/  /'
  echo ""
}

###########################
# Program
###########################

if [ $# -lt 1 ]; then
  show_help
  exit 1
fi

if [ "$1" == "--help" ]; then
  show_help
  exit 0
fi

GROOT=/opt/groot

if [ ! -d "${GROOT}" ]; then
  echo "No groot workspace found, use 'groot_sources' and 'groot_build' to create one."
  exit 1
fi

if [ "$1" == "--list" ]; then
  list_profiles
  exit 0
fi

ROBOT=$1

#grep ${ROBOT} /etc/hosts
#if [ "$?" == "1" ]; then
#   echo "Robot name '${ROBOT}' not found in /etc/hosts."
#   exit 1
#fi
if [ ! -f ~/.unison/gopher.prf ]; then
  echo ""
  echo "Copying gopher unison profile."
  echo ""
  echo "from:"
  echo "  /opt/groot/gopher_ws/src/gopher/gopher_meta/resources/unison/gopher.prf"
  echo "to:"
  echo "  ~/.unison/gopher.prf."
  echo ""
  cp /opt/groot/gopher_ws/src/gopher/gopher_meta/resources/unison/gopher.prf ~/.unison/
fi
if [ ! -f ~/.unison/ignore.prf ]; then
  echo ""
  echo "Copying ignore paths unison profile."
  echo ""
  echo "from:"
  echo "  /opt/groot/gopher_ws/src/gopher/gopher_meta/resources/unison/ignore.prf"
  echo "to:"
  echo "  ~/.unison/ignore.prf."
  echo ""
  cp /opt/groot/gopher_ws/src/gopher/gopher_meta/resources/unison/ignore.prf ~/.unison/
fi


if [ ! -f ~/.unison/${ROBOT}.prf ]; then
  echo ""
  echo "Copying robot specific unison profile."
  echo ""
  echo "from:"
  echo "  /opt/groot/gopher_ws/src/gopher/gopher_meta/resources/unison/${ROBOT}.prf"
  echo "to:"
  echo "  ~/.unison/${ROBOT}.prf."
  echo ""
  cp /opt/groot/gopher_ws/src/gopher/gopher_meta/resources/unison/${ROBOT}.prf ~/.unison/
fi
unison-gtk ${ROBOT}
