#!/bin/bash

# Do not proceed on any error
set -e

# Bail out if the required parameters and not present
if [ $# != 5 ]; then
  echo "InvalidArgumentException: Hermes~swap_and_relaunch packageName, eID, rootDirectory, parentProcessID and restart are the required parameters"
  exit 1
fi

packageName="$1"
eID="$2"
rootDir="$3"
parentProcessId="$4"
restart="$5"

log() {
  echo "$(date +"%Y/%m/%d %H:%M:%S:%3N") $eID $@" >> "$rootDir/log.txt"
}

log "Swapping the old app with new one"
mv "$rootDir/app" "$rootDir/$eID-old"
mv "$rootDir/$eID" "$rootDir/app"
log "Swapping done"

# If parent is alive then kill it
# @todo add tests for this
if [ $parentProcessId != 0 ]; then
  ps --pid $parentProcessId &> /dev/null
  if [ $? == 0 ]; then
    log "Parent process is alive, killing it now"
    kill -9 $parentProcessId
  fi
fi

if [ "$restart" == "false" ]; then
  # RELAUNCH process skipped
  # swapInputData.restart is 'false'
  echo "Relaunch~skipped"

  # Exit with success
  exit 0
fi

log "Launching app with command $rootDir/app/$packageName --updated --eID=$eID"
# @todo add tests
"$rootDir/app/$packageName" --updated --eID="$eID" >/dev/null 2>&1
