#!/usr/bin/env bash

# Find current file directory
# supporting symlinks
WEX_DIR_CLI="$(realpath "$(dirname "$(readlink -f ${BASH_SOURCE[0]})")")/"
WEX_ROOT="$(realpath "${WEX_DIR_CLI}../")/"

# Source .env file if it exists
if [ -f "${WEX_ROOT}/.env" ]; then
    . "${WEX_ROOT}/.env"
fi

. "${WEX_DIR_CLI}/_init.sh"

# Function to handle cleanup on exit or interruption
cleanup() {
    if [ -f "${WEX_POST_EXEC}" ]; then
        rm "${WEX_POST_EXEC}"
    fi
    if [ -f "${WEX_TASK_REDIRECT}" ]; then
        rm "${WEX_TASK_REDIRECT}"
    fi
}

# Trap to handle interruptions and cleanup
trap cleanup EXIT INT TERM

WEX_REQUEST_ID="$(date '+%Y%m%d-%H%M%S-%N')-$$"

# Allow to override python executor
WEX_INTERPRETER=${WEX_INTERPRETER:-${WEX_ROOT}.venv/bin/python}

# Load main python script
${WEX_INTERPRETER} "${WEX_ROOT}__main__.py" --force-request-id "${WEX_REQUEST_ID}" "${@}"

