#!/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
}

if [ -d "/opt/groot/gopher_ws/src/gopher/gopher_robot/unison" ]; then
  PROFILES_DIR=/opt/groot/gopher_ws/src/gopher/gopher_robot/unison
elif [ -d "/opt/groot/gopher_stable_ws/src/gopher/gopher_robot/unison" ]; then
  PROFILES_DIR=/opt/groot/gopher_stable_ws/src/gopher/gopher_robot/unison
elif [ -d "/opt/yujin/amd64/indigo-devel/share/gopher_robot/unison" ]; then
  PROFILES_DIR=/opt/yujin/amd64/indigo-devel/share/gopher_robot/unison
elif [ -d "/opt/yujin/amd64/indigo-stable/share/gopher_robot/unison" ]; then
  PROFILES_DIR=/opt/yujin/amd64/indigo-stable/share/gopher_robot/unison
fi

list_profiles()
{
  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 ${PROFILES_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' 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 "  ${PROFILES_DIR}/gopher.prf"
  echo "to:"
  echo "  ~/.unison/gopher.prf."
  echo ""
  cp ${PROFILES_DIR}/gopher.prf ~/.unison/
fi
if [ ! -f ~/.unison/ignore.prf ]; then
  echo ""
  echo "Copying ignore paths unison profile."
  echo ""
  echo "from:"
  echo "  ${PROFILES_DIR}/ignore.prf"
  echo "to:"
  echo "  ~/.unison/ignore.prf."
  echo ""
  cp ${PROFILES_DIR}/ignore.prf ~/.unison/
fi


if [ ! -f ~/.unison/${ROBOT}.prf ]; then
  echo ""
  echo "Copying robot specific unison profile."
  echo ""
  echo "from:"
  echo "  ${PROFILES_DIR}/${ROBOT}.prf"
  echo "to:"
  echo "  ~/.unison/${ROBOT}.prf."
  echo ""
  cp ${PROFILES_DIR}/${ROBOT}.prf ~/.unison/
fi
unison-gtk ${ROBOT}
