#! /bin/bash

# BioEmergences Workflow - A standalone workflow for embryo processing on personal computers 
# Written in 2015 by BioEmergences CNRS USR bioemergences@inaf.cnrs-gif.fr
# 
# To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
# You should have received a copy of the CC BY-NC-SA 4.0 Dedication along with this software. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode>.

exec > .logs
exec 2>&1

cd "$(dirname "$0")"

VERSION=1.10

EXIT_OK=0
EXIT_UPDATE_AVAILABLE=1

action="$1"

if [ "${action}" == "--restart" ]
then
  sleep 1
fi

result="OK"

ping -c 1 http://bioemergences.iscpif.fr > /dev/null 2>&1
if [ $? -eq 0 ]
then
  if [ "${action}" == "--dry" ]
  then
    result="$(curl -s 'http://bioemergences.iscpif.fr/bioemergences/php/check_workflow_update.php?a=dry&v='${VERSION}'&o='$(uname))"
  else
    curl -o patch.tar.gz -s 'http://bioemergences.iscpif.fr/bioemergences/php/check_workflow_update.php?v='${VERSION}'&o='$(uname)
    result="$(head -c 5 patch.tar.gz)"
  fi
fi

if [ "${result}" != "OK" -a "${result}" != "ERROR" ]
then
  if [ "${action}" == "--dry" ]
  then
    echo 'Update available'
    rm .logs
    exit ${EXIT_UPDATE_AVAILABLE}
  fi  

  tar -xf patch.tar.gz

  while read line
  do
    perm=$(echo "${line}" | awk '{print $1}')
    file="${line:$((1 + ${#perm}))}"

    chmod ${perm} "${file}"
  done < .updated

  if [ -e CHANGES.txt ]
  then
    cat CHANGES.txt >> .changes
    rm -f CHANGES.txt
  fi

  mv .changes CHANGES.txt

  if [ "$(uname)" == "Darwin" ]
  then
    sed -i '' 's/VERSION='${VERSION}'/VERSION='$(cat .version)'/' update
  else
    sed -i 's/VERSION='${VERSION}'/VERSION='$(cat .version)'/' update
  fi

  rm -f .version
  rm -f .updated
  rm -f patch.tar.gz

  ./update --dry
  if [ $? -ne 0 ]
  then
    echo "Still some work to do"
    ./update ${action}
    rm .logs
    exit $?
  fi
elif [ "${action}" == "--dry" ]
then
  echo "BioEmergences Workflow is up-to-date"
  rm .logs
  exit ${EXIT_OK}
fi

if [ "${action}" == "--restart" ]
then
  echo "Restarting the application..."
  if [ "$(uname)" == "Darwin" ]
  then
    open BioEmergences.app
  else
    ./BioEmergences
  fi
fi

rm -f patch.tar.gz
rm .logs

