#! /bin/bash

# Arguments:
# ${@} = Remaining args to pass to the command

# Halt on error
set -e

# Mounts for container
mounts="{{ mounts }}"
optional_mounts="{{ optional_mounts }}"
# Additional arguments for apptainer
apptainer_args="{{ apptainer_args }}"
# Sif file path
sif_file="$(dirname $0)/{{ relative_sif_file }}"
# Command to run in container
command="{{ command }}"
# Options and arguments to pass to command
command_args="{{ command_args }}"

{% if optional_mounts|length %}
# Filter out optional mounts that are non-existent
IFS="," read -ra optional_mount_paths <<< "$optional_mounts"

validated_mounts=()

for mount_path in "${optional_mount_paths[@]}"; do
    host_path="${mount_path%%:*}"

    if [[ -d "$host_path" || -f "$host_path" ]]; then
        validated_mounts+=("$mount_path")
    fi
done

mounts="${mounts},$(IFS=','; echo "${validated_mounts[*]}")"

{% endif -%}
# Raise an error if sif file does not exist
if [[ ! -f ${sif_file} ]]; then
    echo "ERROR: sif file ${sif_file} does not exist" 1>&2
    exit 1
fi

# add mounts of host binaries into /usr/bin
for i in {{ host_binaries }}; do
    binary=$(which $i)
    mounts="${mounts},${binary}:/usr/bin/${i}"
done

# Set up mounts if any have been configured
if [[ ! -z ${mounts} ]]; then
    opts="-B ${mounts}"
fi

opts=${opts}" --env DISPLAY=${DISPLAY}"
opts=${opts}" ${apptainer_args}"


if [[ -n "${DEPLOY_TOOLS_VERBOSE}" ]]; then
    set -x
fi
apptainer exec ${opts} ${sif_file} ${command} ${command_args} "${@}"
