#!/bin/bash
license_server={license_file_or_server}
filename=${0%.sh}
job_dir=`dirname "$(realpath $0)"`
docker_image={docker_image}
image_name={image_name}
sif_cache_dir={sif_cache_dir}

# Convert Docker image to local SIF if not already cached
mkdir -p "$sif_cache_dir"

sif_path="$sif_cache_dir/$image_name.sif"

# Pull image if not cached
if [ ! -f "$sif_path" ]; then
    echo "Pulling image {docker_image} to $sif_path ..."
    apptainer pull "$sif_path" "docker://$docker_image"
    if [ $? -ne 0 ]; then
        echo "Failed to pull image"
        exit 1
    fi
fi

# GPU support
gpu_flags=""
if [ -n "$CUDA_VISIBLE_DEVICES" ]; then
    gpu_flags="--nv"
    export APPTAINERENV_CUDA_VISIBLE_DEVICES="$CUDA_VISIBLE_DEVICES"
fi

# License server envvar
export APPTAINERENV_ACELLERA_LICENCE_SERVER=${ACELLERA_LICENCE_SERVER:-$license_server}

# Run the container
exec apptainer run --cleanenv --home /data $gpu_flags \
    --bind "$job_dir:/data" \
    --pwd /data \
    "$sif_path" \
    --input-json "$filename/inputs.json" /data

exit_code=$?

if [ $exit_code -ne 0 ]; then
    echo "Error in running application. Check logs..."
    exit $exit_code
fi