#!/bin/bash

set -eu -o pipefail

if [[ ${EUID} -ne 0 ]]; then
    echo "This script should be run as root." > /dev/stderr
    exit 1
fi

readonly updater_service="cloudron-updater"

if [[ $# == 1 && "$1" == "--check" ]]; then
    echo "OK"
    exit 0
fi

if [[ $# != 2 ]]; then
    echo "Usage: update.sh <sourceDir> <logFile> arguments required"
    exit 1
fi

function log() {
  echo -e "$(date +'%Y-%m-%dT%H:%M:%S')" "==> update: $1"
}

readonly source_dir="${1}"
readonly log_file="${2}"

readonly installer_path="${source_dir}/scripts/installer.sh"

log "updating Cloudron with ${source_dir}"

systemctl reset-failed "${updater_service}" 2>/dev/null || true

# this script is invoked as a task. installer.sh will systemctl stop at some point and that will stop all the tasks
# installer.sh is thus run as a separate unit name so that it doesn't get killed during the stoptask.sh
# StandardError will follow StandardOutput in default inherit mode. https://www.freedesktop.org/software/systemd/man/systemd.exec.html
if ! systemd-run --property=OOMScoreAdjust=-1000 --unit "${updater_service}" --wait -p StandardOutput=append:${log_file} ${installer_path}; then
    echo "${updater_service} failed to run" # this only happens if the path to installer is wrong
fi

# if the install script succeeded, the following code is never run since this script will get killed
exit_code=$(systemctl show "${updater_service}" -p ExecMainCode | sed 's/ExecMainCode=//g')
echo "${updater_service} finished with exit code ${exit_code}"
exit "${exit_code}"
