#!/bin/sh
set -eux

pkg="singularity-container"
AUTOPKGTEST_TMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)

echo "Testing inside tempdir ${AUTOPKGTEST_TMP}"
cd "${AUTOPKGTEST_TMP}"

IMAGE_NAME="test_image.sif"
SANDBOX_DIR="sandbox_dir/"

# Test: Build a Singularity Image from Docker container
singularity build $IMAGE_NAME docker://busybox:latest
echo "[PASS] Build from Docker container"

# Test: Running a Singularity Container
OUTPUT=$(singularity run $IMAGE_NAME echo "Hello, Singularity!")
test "$OUTPUT" = "Hello, Singularity!"
echo "[PASS] Run a Singularity container"

# Test: Executing a Specific Command Inside a Container
singularity exec $IMAGE_NAME ls /
echo "[PASS] Executed command inside a container"

# Test: Shell Access (just a basic test as shell access is interactive)
echo "exit" | singularity shell --writable-tmpfs $IMAGE_NAME
echo "[PASS] Shell access is interactive"

# Test: Inspecting a Singularity Image (checking for existence of output)
INSPECT_OUTPUT=$(singularity inspect $IMAGE_NAME)
echo "[PASS] Inspect Singularity image"

# Test: Convert Image to Sandbox Format
singularity build --sandbox $SANDBOX_DIR $IMAGE_NAME
test -d "$SANDBOX_DIR"
echo "[PASS] Convert image to sandbox"

# Test: Mounting Bind Paths and Directories
mkdir -p /tmp/singularity_bind_test
echo "bind_test" > /tmp/singularity_bind_test/test.txt
BIND_OUTPUT=$(singularity exec --bind /tmp/singularity_bind_test:/mnt $IMAGE_NAME cat /mnt/test.txt)
test "$BIND_OUTPUT" = "bind_test"
echo "[PASS] Mounting bind paths and directories"

# Cleanup
rm -f $IMAGE_NAME
rm -rf $SANDBOX_DIR
rm -rf /tmp/singularity_bind_test
rm -rf $AUTOPKGTEST_TMP

echo "All tests completed!"
