#!/usr/bin/env bash
# This script is intended to be sourced, not executed directly.

dayp="$1"  # Profile code [loal|slurm]
gbuild="$2" # genome build code [hg38|b37]
remote_call="$3" # remote call flag

echo "Requesting profile: $dayp"
DP=$DAY_PROJECT

if [[ -z "$dayp" ]]; then
    echo "ERROR: No profile specified, please specify [slurm|local] ([hg38|b37])"
    return 1
fi

# Attempt to deactivate any existing environment
source bin/day_deactivate &> /dev/null 
echo "Attempting to deactivate existing environments & re-init with --project $DP ."
. dyoainit --project $DP --deactivate &> /dev/null
export DAY_PROFILE=$dayp


# Check if DAY_ROOT is set
if [[ -z "$DAY_ROOT" ]]; then
    echo "ERROR: DAY_ROOT is not set. Have you executed 'source dyoainit'? Use -h for help."
    return 2
fi

# Handle help argument
if [[ "$1" =~ ^(-h|--help|help)$ ]]; then
    echo "Usage: day-activate [profile]"
    echo "This script activates a Daylily analysis profile."
    echo "Valid profiles are located in 'config/day_profiles/'."
    echo "Example: day-activate local"
    return 0
fi

export DAY_PROFILE_DIR="$DAY_ROOT/config/day_profiles/$DAY_PROFILE"
if [[ ! -d "$DAY_PROFILE_DIR" ]]; then
    colr "ERROR: Profile directory: $DAY_PROFILE_DIR does not exist." "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    echo "Have you run 'day-activate'?"
    return 3
fi

if [[ "$remote_call" == "remote" ]]; then
    echo "Remote call detected. Activating conda hack"
    . "$HOME/miniconda3/etc/profile.d/conda.sh"
    export DAY_REMOTE_EXE="remote"
else
    unset DAY_REMOTE_EXE
fi

conda activate DAYOA
conda_ret_code=$?
if [[ "$conda_ret_code" != "0" ]]; then
    colr "ERROR: conda activate DAYOA failed with return code $conda_ret_code."  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    return 4
fi

source bin/util/profile_freshness_warn.bash
if [[ "$?" == "3" ]]; then
    colr "ERROR: source bin/util/profile_freshness_warn.bash"  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    return 4
fi

if ! which yq &>/dev/null; then
  echo "yq not found. Installing via conda in base environment..."
  conda install -c conda-forge yq -y || {
    echo "Failed to install yq."
    return 3
  }
else
  echo "yq is already installed."
fi

CONFIG_FILE=~/.config/daylily/daylily_cli_global.yaml
git_tag=$(yq -r '.daylily.git_tag' "$CONFIG_FILE")
export SENTIEON_TMPDIR=$(yq -r '.daylily.sentieon_tmpdir' "$CONFIG_FILE")
export TMPDIR=$SENTIEON_TMPDIR
export SENTIEON_LICENSE_YAM=$(yq -r '.daylily.sentieon_lic_path' "$CONFIG_FILE")
export SENTIEON_INSTALL_DIR=$(yq -r '.daylily.sentieon_install_dir' "$CONFIG_FILE")
export PATH="$PATH:$SENTIEON_INSTALL_DIR/bin/"
export SENTIEON_LICENSE=''

# Test if file exists
if [[ ! -f "$SENTIEON_LICENSE_YAM" ]]; then
    echo "WARNING: sentieon lic file $SENTIEON_LICENSE_YAM not found."

    detected_license=$(ls /fsx/data/cached_envs/*lic)
    if [[ ! -f "$detected_license" ]]; then
        echo "WARNING: sentieon lic file not detected in '/fsx/data/cached_envs/*lic' ."
        echo "If you try to use any of the sentieon tools, you will get an error."
        sleep 2
    else
        echo "Detected sentieon license file: $detected_license will be used and overrides what is in ~/.config/daylily/daylily_cli_global.yaml"
        export SENTIEON_LICENSE=$detected_license
    fi
else
    echo "Using sentieon license file: $SENTIEON_LICENSE_YAM from ~/.config/daylily/daylily_cli_global.yaml"
    export SENTIEON_LICENSE=$SENTIEON_LICENSE_YAM
fi

if [[ ! -f ~/.config/daylily/$git_tag ]]; then
    echo ""
    echo "!!!!"
    echo "!!!!"
    echo "    WARNING: gittag:$git_tag not found touched in  ~/.config/daylily/$git_tag "
    echo "     This might be fine if you have cloned a more recent release of daylily compared to the tagged version used to create this ephemeral cluster."
    echo "     ... however, this is not expected. If you are running an ephemeral cluster headnode for days+, this is not the intended use of daylily, a fresh build might be called for."
    echo "     This is checked by testing if ~/.config/daylily/$git_tag exists ."
    echo "!!!!"
    sleep 3
fi



# Verify profile exists
profile_info="$DAY_ROOT/config/day_profiles/$1/templates/profile.info"
if [[ -f "$profile_info" ]]; then
    # Extract environment variables from profile.info
    env_val=$(grep 'env_var_val' "$profile_info" | cut -d ':' -f 2)
    if [[ "$env_val" != "$DAY_PROFILE" ]]; then
        colr "ERROR: Profile '$1' does not match the expected environment variable value."  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
        return 1
    fi
    env_script=$(grep 'env_script' "$profile_info" | cut -d ':' -f 2)
    mgps1val=$(grep 'terminal_abbreviation' "$profile_info" | cut -d ':' -f 2)

    # Source the environment script
    source "$env_script"
    pe_ret_code=$?
    export DYPS1="$mgps1val"
else
    colr "ERROR: Profile '$1' not found."  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    return 1
fi

# Check for 'colr' command
if ! command -v colr &> /dev/null; then
    colr "ERROR: 'colr' package is missing. Things will probably work, but not look fabulous."  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    sleep 2
fi

# Check for errors during activation
if [[ "$pe_ret_code" != "0" ]]; then
    source bin/util/col_error.bash
    colr "ERROR: Activation failed with return code $pe_ret_code."  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    colr ""  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    colr  "Have you run 'day-build'? If so, try 'bin/day_deactivate reset; source dyoainit; day-activate local;'"  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    return $pe_ret_code
else


    gbuild_ret_code=0
    if [[ "$gbuild" != "" ]]; then
        source bin/day_set_genome_build $gbuild
        gbuild_ret_code=$?
    else
        colr "Skipping genome build activation."  "$DY_WI1" "$DY_IB2" "$DY_IS1" 1>&2
    fi

    if [[ "$gbuild_ret_code" != "0" ]]; then
        colr  "ERROR:  dy-g $gbuild ($gbuild_ret_code)  failed." "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
        return 5
    fi
    colr "       _______ GREAT SUCCESS _______       " "$DY_IT0" "$DY_IB0" "$DY_IS1"
    export PS1="$DYPS1$PS1"
fi

return 0
