#!/bin/bash -ex

# If this file is renamed, you MUST also update the --catchup function in iworx-vm

# This script cannot have external dependencies unless you figure out how to make that
# work for the iworx-vm tool

VERBOSE=0

if [[ "$0" == *"--verbose"* ]]; then
  VERBOSE=1
fi

cd ~iworx/bin
./php parallel-test.php --make-pex-files

# To work around temporary failues, try again if the initial attempt fails.
~iworx/cron/license.pex --sync || sleep 5; ~iworx/cron/license.pex --sync

cp -f ~iworx/etc/init.d/iworx /etc/init.d/iworx

cp -f ~iworx/etc/nodeworx-menu.ini-dist ~iworx/etc/nodeworx-menu.ini
cp -f ~iworx/etc/siteworx-menu.ini-dist ~iworx/etc/siteworx-menu.ini

IW_NEWEST_VERSION=$(find ~iworx/include/Upgrade/Version/ | grep '[[:digit:]].php' | sed -r 's/.+Version\/(.+).php/\1/' | sed 's/\//./g' | sort -rn -t. -k1,1 -k2,2 -k3,3 | head -n1)
~iworx/bin/upgrade.pex --version $IW_NEWEST_VERSION
~iworx/bin/iworx-upgrade.pex --upgrade --version Next

if [ $VERBOSE ]; then
  echo $IW_NEWEST_VERSION
  ~iworx/bin/iworx-upgrade.pex --status --version $IW_NEWEST_VERSION
  ~iworx/bin/iworx-upgrade.pex --status --version Next
fi
