#!/usr/bin/env bash

# Configure the script to exit when a command fails.
set -e

# ===== SHARED CODE =====

: ${SCRIPTS_ROOT:="$(dirname $0)"/../../scripts}
export SCRIPTS_ROOT
source "${SCRIPTS_ROOT:?}"/util.sh

# ===== CONSTANTS =====

: ${SELF:="$(basename $0)"}
LOCAL_RUN_DIR="${REPOSITORY_ROOT:?}"/local-run
SELF_SCRIPTS="${LOCAL_RUN_DIR:?}"/scripts

# ===== HELPER FUNCTIONS =====

description() {
	cat <<EOF
${Bold}Updates the Prose Pod API and the repositories it depends on to get the latest updates.${Bold_Off}

This script pulls the latest changes from $(format_code prose-pod-api) and $(format_code prose-pod-system),
plus $(format_code prose-pod-server) if you have the repository locally.
Use $(format_code task local:build) to build the images locally.
EOF
}

usage() {
	cat <<EOF
$(format_title 'Usage:')
  You want to update without changing the checked out branches:
    $(format_command "${SELF%' --'}")
  You want to test a hotfix made on a specific branch of the Prose Pod API:
    $(format_command "${SELF:?}") $(format_arg --api-branch=BRANCH)

$(format_title 'Options:')
  $(format_subtitle 'Main options:')
    $(format_flag --api-branch=BRANCH)
      Choose the branch to checkout in $(format_code prose-pod-api).

  $(format_subtitle 'Miscellaneous options:')
    $(format_flag --help)
      Explains what the command does and how to use it.
    $(format_flag --dry-run)
      Do a dry run (i.e. print what would be executed instead of running it).
    $(format_flag --debug)
      Log debug messages when running the script.
    $(format_flag --trace)
      Log tracing messages when running the script.
EOF
}

help() {
	printf "$(description)\n"
	echo ''
	printf "$(usage)\n"
	exit 0
}

# ===== ARGUMENT PARSING =====

for arg in "$@"; do
	case $arg in
		--api-branch=*)
			API_BRANCH="${arg#'--api-branch='}"
			info "Will use branch $(format_code $API_BRANCH) for $(format_code prose-pod-api)."
			;;
		--help) help ;;
		--dry-run) export DRY_RUN=1 ;;
		--debug) export LOG_DEBUG=1 ;;
		--trace) export LOG_TRACE=1 ;;
		*) die "Unknown argument: $(format_code $arg).\n$(usage)" ;;
	esac
done

# Recompute log levels.
source "${BASH_TOOLBOX:?}"/log.sh

# ===== MAIN LOGIC =====

# Prevent running if unnecessary.
if ! git ls-remote --exit-code --heads origin "$(git rev-parse --abbrev-ref HEAD)"; then
	info 'Branch doesn’t exist on remote, not updating.'
	exit 0
fi
if [ -z "$(git diff origin/"$(git rev-parse --abbrev-ref HEAD)" 2>/dev/null)" ]; then
	info 'Remote doesn’t have new commits, not updating.'
	exit 0
fi

info "Updating $(format_code prose-pod-api)…"
if [ -n "${API_BRANCH}" ]; then
	edo git -C "${PROSE_POD_API_DIR:?}" checkout "${API_BRANCH:?}" 2>/dev/null \
	|| edo git -C "${PROSE_POD_API_DIR:?}" checkout -t origin/"${API_BRANCH:?}"
fi
edo git -C "${PROSE_POD_API_DIR:?}" pull
edo git -C "${PROSE_POD_API_DIR:?}" submodule update --init --remote

# Update scenarios
. "${SELF_SCRIPTS:?}"/scenarios-update
