#!/bin/sh
set -e

# CRITICAL: leave source tree
cd /

# Force use of installed package
unset PYTHONPATH

for py in $(py3versions -s); do
    echo "=== Testing with $py ==="

    $py - <<'EOF'
import ptufile
import numpy
import tempfile
import os
import subprocess

print("✔ Imported ptufile")

# Check where the Python module is loaded from
print("ptufile module:", ptufile.__file__)
assert ptufile.__file__ is not None

# Ensure the C extension is present and loaded
try:
    import ptufile._ptufile as ext
except ImportError as e:
    raise AssertionError("C extension ptufile not found") from e

print("✔ C extension loaded:", ext.__file__)
assert "dist-packages" in ptufile.__file__, ptufile.__file__
assert ext.__file__.endswith(".so"), ext.__file__

# Verify shared library dependencies using ldd
print("Running ldd on:", ext.__file__)
out = subprocess.check_output(["ldd", ext.__file__], text=True)
print(out)

# Ensure libc is linked and no dependencies are missing
assert "libc.so.6" in out, "libc missing in ldd output"
assert "not found" not in out, "Missing shared library detected"

# Minimal functional test using the C extension
data = numpy.zeros((2, 2, 4), dtype=numpy.uint32)

tmp = tempfile.NamedTemporaryFile(suffix=".bin", delete=False)
tmp.close()

try:
    # Call a core function to ensure runtime correctness
    ptufile.binwrite(tmp.name, data, 1e-9, pixel_resolution=1.0)
    print("✔ binwrite OK")

    # Verify output file was created and is not empty
    assert os.path.exists(tmp.name), "Output file missing"
    assert os.path.getsize(tmp.name) > 0, "Output file is empty"

    print("✔ File write OK")

finally:
    os.unlink(tmp.name)

print("✔ All checks passed")

EOF
done

echo "=== All Python versions passed ==="
