Commit e7135193 authored by Bogdan Vacaliuc's avatar Bogdan Vacaliuc
Browse files

add usage, environment injection and arg validation

parent 52c67602
Loading
Loading
Loading
Loading
+74 −7
Original line number Diff line number Diff line
#!/bin/bash
TMP=$(mktemp)
ENV=${1:-mantid} ; shift
CMD=${2:-ScriptToExecuteWithProfile.py} ; shift
_usage() {
    echo "usage: $0 <environment> [--classic] <script> [tool arguments]"
    if [[ "$OSTYPE" == "darwin"* ]]; then
        echo "MACOS is unsupported for mantid-profiler at this time due to an issue in psutil."
    fi
}

# execute main app in background
# overwrite these values with environment injection e.g.
# PIXI_PREFIX=path-to-parent-folder nsd-mantid-profile-wrap.sh mantid_dev --classic script.py
# PROFILE_ENV=mantid nsd-mantid-profile-wrap.sh mantid --classic script.py
# PROFILE_OPT="--outfile path-to-html" nsd-mantid-profile-wrap.sh mantid --classic script.py

PIXI_PREFIX="${PIXI_PREFIX:=/usr/local/pixi}"
PROFILE_ENV="${PROFILE_ENV:=mantid_dev}"
read -r -a PROFILE_OPT <<< "${PROFILE_OPT//[\(\)]/}"	# ensure PROFILE_OUT is an array

# select the environment to use
ENV=
if [ -n "$1" ]; then
    case $1 in
    --h*|-h)
        _usage
        exit 0
        ;;
    *)
        ENV="$1"
        shift
        ;;
    esac
else
    echo "Must specify an environment to activate"
    _usage
    exit 255
fi

# consume option parameters
while [[ ${1} =~ ^- ]] ; do
    case $1 in
    --classic)  # supported for nsd-conda-wrap.sh so accept it without fuss
        ;;
    --debug)    # print commands as they are executed
        set -x
        ;;
    *)
        break
        ;;
    esac
    shift
done

# select the script to use
CMD="${1:-}"
shift
if [ -z "$CMD" ] ; then
    echo "Must specify a script to run"
    _usage
    exit 255
fi

# execute main app in background
TMP=$(mktemp)
nsd-conda-wrap.sh ${ENV} --classic ${CMD} $@ > ${TMP} & pid=$!
# https://unix.stackexchange.com/questions/427115/listen-for-exit-of-process-given-pid-pid
trap 'tail --pid $pid -f /dev/null' EXIT

# deal with background app under CTRL-C and exit conditions
trap 'set -x ; kill -HUP $pid' SIGINT
trap 'set -x ; wait $pid' EXIT

# execute profile process in foreground
nsd-conda-wrap.sh mantid_dev --classic -m mantidprofiler ${pid} --outfile ${TMP}.html && echo "Wrote ${TMP}.html"
args=("$PROFILE_ENV" "--classic" "-m" "mantidprofiler")
args+=(${PROFILE_OPT[@]})
args+=("${pid}")
if nsd-conda-wrap.sh ${args[@]} ; then
    # https://superuser.com/a/1732848
    if [[ "${PROFILE_OPT[@]}" =~ "--outfile ([^ ]+) " ]]; then
        echo "Wrote ${BASH_REMATCH[1]}"
    else
        echo "Wrote $(pwd)/profile.html"
    fi
fi