#!/usr/bin/env bash

# Deprecated compatibility shim. Source this file to reproduce the old dyinit
# behavior via the CLI-owned headnode bootstrap flow.

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    echo "Error: this script must be sourced." >&2
    echo "Usage: source $0 [--project <project_name>] [--skip-project-check]" >&2
    exit 3
fi

dyinit_repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "Warning: dyinit is deprecated. Use 'source ~/projects/daylily-ephemeral-cluster/activate' and 'eval \"\$(daylily-ec headnode init --emit-shell --non-interactive)\"' instead." >&2

# shellcheck source=/dev/null
source "${dyinit_repo_root}/activate" || return 1

if ! command -v daylily-ec >/dev/null 2>&1; then
    echo "Error: daylily-ec is not available after sourcing ${dyinit_repo_root}/activate." >&2
    return 1
fi

dyinit_has_help=0
dyinit_has_emit_shell=0
for arg in "$@"; do
    case "$arg" in
        -h|--help|help)
            dyinit_has_help=1
            ;;
        --emit-shell)
            dyinit_has_emit_shell=1
            ;;
    esac
done

if [[ "$dyinit_has_help" == "1" ]]; then
    daylily-ec headnode init "$@"
    return $?
fi

if [[ "$dyinit_has_emit_shell" != "1" ]]; then
    set -- "$@" --emit-shell
fi

dyinit_shell="$(daylily-ec headnode init "$@")" || return $?
eval "${dyinit_shell}"

unset arg
unset dyinit_has_emit_shell
unset dyinit_has_help
unset dyinit_repo_root
unset dyinit_shell

return 0
