#!/usr/bin/env bash

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

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

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

LOCAL_RUN_DIR="${REPOSITORY_ROOT:?}"/local-run
SELF_SCRIPTS="${LOCAL_RUN_DIR:?}"/scripts
source "${SELF_SCRIPTS:?}"/constants.sh
BASE_SCENARIO_NAME="${DEFAULT_SCENARIO_NAME:?}"
: ${BASE_SCENARIOS_DIR:="${SCENARIOS_DIR:?}"}

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

unset SCENARIO_NAME

for arg in "$@"; do
	case $arg in
		--based-on=*)
			BASE_SCENARIO_NAME="${arg#'--based-on='}"
			;;
		--help) die Unsupported ;;
		--dry-run) export DRY_RUN=1 ;;
		--debug) export LOG_DEBUG=1 ;;
		--trace) export LOG_TRACE=1 ;;
		*)
			if ! [ -v SCENARIO_NAME ]; then
				SCENARIO_NAME="$arg"
			else
				die "Unknown argument: $(format_code "$arg").\n$(usage)"
			fi
			;;
	esac
done

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

edo source "${SELF_SCRIPTS:?}"/scenario-files.sh

[ -d "${SCENARIO_DIR:?}" ] && die "The scenario $(format_code "${SCENARIO_NAME:?}") already exists. Would you like to derive a new one from it? If so, run $(format_code "task local:scenarios:create -- '${SCENARIO_NAME:?}-2' --based-on='${SCENARIO_NAME:?}'")"

BASE_SCENARIO_DIR="${BASE_SCENARIOS_DIR:?}"/"${BASE_SCENARIO_NAME:?}"
info "Will create a new scenario named $(format_code "${SCENARIO_NAME:?}") based on $(format_code "$(echo "${BASE_SCENARIO_DIR:?}" | awk -F / -v OFS=/ '{ print $(NF-2), $(NF-1), $NF }')")."

[ -d "${BASE_SCENARIO_DIR:?}" ] || die "Base scenario $(format_code "${BASE_SCENARIO_DIR:?}") not found."

edo mkdir -p "${SCENARIO_DIR:?}"

copy-if-exists() {
	local file_path="${1:?}"
	if [ -e "${BASE_SCENARIO_DIR:?}"/"${file_path:?}" ]; then
		edo cp -RLf "${BASE_SCENARIO_DIR:?}"/"${file_path:?}" "${SCENARIO_DIR:?}"/"${file_path:?}"
	else
		trace "Cannot $(format_code cp) $(format_code "${file_path:?}"): Not found."
		case "${file_path:?}" in
			*/) edo mkdir -p "${SCENARIO_DIR:?}"/"${file_path:?}" ;;
			*) edo mkdir -p "$(dirname "${SCENARIO_DIR:?}"/"${file_path:?}")" ;;
		esac
	fi
}

copy-if-exists 'prosody/'
copy-if-exists 'coredns/'
copy-if-exists 'prose-config/'
copy-if-exists 'prose-pod-api-data/'
copy-if-exists 'prose-pod-server-data/'
copy-if-exists 'prose-backups/'
copy-if-exists constants.sh
copy-if-exists "$(basename "${ENV_FILE:?}")"
copy-if-exists "$(basename "${DNS_ZONE_FILE:?}")"
copy-if-exists "$(basename "${DATABASE_PATH:?}")"
copy-if-exists "$(basename "${MAILPIT_DATABASE_PATH:?}")"

# NOTE: When running in a GitHub Action, some commands fail because
#   `$LOCAL_RUN_DIR/scenarios/$SCENARIO_NAME/*` belong to `runner:docker`.
# NOTE: Because of `set -e`, we’d have to use `[ … ] && … || :`.
#   Let’s use `if [ … ]; then …; fi` instead for clarity.
if [ -n "$GITHUB_ACTIONS" ]; then
	edo sudo chmod -R a+w "${SCENARIO_DIR:?}"/{prosody,prose-pod-api-data,prose-pod-server-data,prose-backups}
fi
