#!/usr/bin/env bash
#
# key 8ec1aa8 2023-08-15 10:40:31 -0400

arch=$1
title=$2

if [ $# -eq 0 ] ;  then
  echo "usage: sbupdate-title  <x86_64-linux || i386-mac> <application name>"
  exit 0
else
  echo "Updating ${arch}/${title}"
fi

if [ -e ${HOME}/.sbgridrc ] ; then
  SYNC_SERVER="sync.sbgrid.org"
  source ${HOME}/.sbgridrc
else
  echo "${HOME}/.sbgridrc not found. This script cannot continue"
  exit 1
fi

if [ $(uname) == "Linux" ] ; then
  rsync_cmd="${INSTALL_TARGET}/x86_64-linux/system/rsync/current/bin/rsync"
elif [ $(uname) == "Darwin" ] ; then
  rsync_cmd="${INSTALL_TARGET}/i386-mac/system/rsync/current/bin/rsync" 
else
  echo "Unsupported OS. Exiting"
  exit 0
fi

if [ ! -x "${rsync_cmd}" ] ; then
  echo "Cannot find a usable rync. Exiting." 
  exit 1
elif [ ! -e "${INSTALL_TARGET}" ] ; then
  echo "Cannot find installation target. Exiting." 
  exit 1
else
  export RSYNC_PASSWORD="${SB_SITEKEY}"
  export USER="${SB_SITENAME}"
  logdir="$HOME/.sbgrid/logs"

  mkdir -p ${logdir}
  mkdir -p "/${INSTALL_TARGET}/${arch}/${title}/"
  
  now=$(date +%Y%m%d)
  rsync_args="-zrlptODPv --log-file=${logdir}/sbgrid-admin-${now}.log --delete-during"
  ${rsync_cmd} ${rsync_args} "rsync://$SYNC_SERVER/$SB_SITENAME/main/programs/${arch}/${title}/" "/${INSTALL_TARGET}/${arch}/${title}/"

  if [ $? != 0 ] ; then
    echo "Update likely failed"
    echo "Please send ${logdir}/sbgrid-admin-${now}.log to bugs@sbgrid.org with a breif description of your issue."
  else
    echo "Update successful"
  fi
fi