#!/usr/bin/env bash
set -euo pipefail

usage() {
    cat <<'EOF'
Usage: install-daylily-headnode-tools [-h|--help]

Installs a small set of Daylily helper assets on a ParallelCluster head node:
  - Copies daylily CLI config files into ~/.config/daylily
  - Installs the `day-clone` helper into /usr/local/bin (if possible) and ~/.local/bin
  - Optionally runs `install_miniconda` and `init_dayec` from the packaged resources

This script is safe to run from any working directory as long as the
daylily-ephemeral-cluster package is installed (or DAYLILY_EC_RESOURCES_DIR is set).
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
    usage
    exit 0
fi

resolve_daylily_res_dir() {
    if [[ -n "${DAYLILY_EC_RESOURCES_DIR:-}" ]]; then
        echo "${DAYLILY_EC_RESOURCES_DIR}"
        return 0
    fi
    if command -v daylily-ec >/dev/null 2>&1; then
        daylily-ec resources-dir
        return 0
    fi
    local script_dir repo_root
    script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    repo_root="$(cd "${script_dir}/.." && pwd)"
    if [[ -d "${repo_root}/config" && -d "${repo_root}/bin" ]]; then
        echo "${repo_root}"
        return 0
    fi
    echo "Error: could not resolve Daylily resources dir. Set DAYLILY_EC_RESOURCES_DIR or install daylily-ephemeral-cluster." >&2
    return 1
}

REPO_ROOT="$(resolve_daylily_res_dir)" || exit 1
CONFIG_SOURCE_DIR="$REPO_ROOT/config"
TARGET_CONFIG_DIR="$HOME/.config/daylily"

mkdir -p "$TARGET_CONFIG_DIR"

cp "$CONFIG_SOURCE_DIR/daylily_cli_global.yaml" "$TARGET_CONFIG_DIR/daylily_cli_global.yaml"
cp "$CONFIG_SOURCE_DIR/daylily_available_repositories.yaml" "$TARGET_CONFIG_DIR/daylily_available_repositories.yaml"

# Install day-clone into a system-wide location if possible, otherwise fall back to ~/.local/bin
INSTALL_TARGET="/usr/local/bin/day-clone"
if command -v sudo >/dev/null 2>&1; then
    if sudo install -m 0755 "$REPO_ROOT/bin/headnode_utils/day-clone" "$INSTALL_TARGET"; then
        echo "day-clone installed to $INSTALL_TARGET"
 
    else
        echo "Warning: failed to install day-clone to $INSTALL_TARGET with sudo. Falling back to user installation." >&2
    fi
fi

cd "$REPO_ROOT" || echo "Failed to cd to $REPO_ROOT" >&2
"$REPO_ROOT/bin/install_miniconda" || echo "failed to install miniconda"
"$REPO_ROOT/bin/init_dayec" || echo "failed to install day-ec"

reference_bucket=$(awk '/^[[:space:]]*Script: s3:/{match($0,/s3:\\/\\/([^/]+)/,a); print a[1]; exit}' /opt/parallelcluster/shared/cluster-config.yaml) || echo "failed to set ref bucket"
sed -i "s|<REF-BUCKET-NAME>|$reference_bucket|g"  "$REPO_ROOT/etc/analysis_samples_template.tsv" || echo "failed to regsub anasamptemp.tsv"


USER_BIN_DIR="$HOME/.local/bin"
mkdir -p "$USER_BIN_DIR"
install -m 0755 "$REPO_ROOT/bin/headnode_utils/day-clone" "$USER_BIN_DIR/day-clone"
echo "day-clone installed to $USER_BIN_DIR/day-clone. Ensure $USER_BIN_DIR is on your PATH."
