#!/bin/sh
set -eux

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

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

# Setup make a zot registry
docker run -d -p 5000:5000 --name oras-autopkgtest ghcr.io/project-zot/zot-linux-amd64:latest

# Wait for zot to get up and running
sleep 5

exit_code=0
# Test: Push a simple file
echo "hello world" > artifact.txt
oras push --plain-http --insecure localhost:5000/hello-artifact:v1 \
    --artifact-type application/vnd.acme.rocket.config \
    artifact.txt:text/plain || exit_code=$?
if [ "$exit_code" != "0" ]; then
    echo "Exited with exit code: $exit_code"
fi

# Test: Pull the same file and check checksum
md5sum artifact.txt > checkmd5.md5
rm -f artifact.txt
oras pull localhost:5000/hello-artifact:v1
md5sum -c checkmd5.md5 || exit 1
rm -f artifact.txt

# Test: View referrers
oras discover localhost:5000/hello-artifact:v1

# Cleanup
trap "docker rm $(docker stop oras-autopkgtest)" 0 INT QUIT ABRT PIPE TERM

echo "All tests completed!"
