#!/bin/bash
set -e
set -x

pkg=orthanc-wsi
CUR_DIR=`pwd`
service_name=orthanc

if [ "${AUTOPKGTEST_TMP}" = "" ] ; then
  AUTOPKGTEST_TMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)
  trap "rm -rf ${AUTOPKGTEST_TMP}" 0 INT QUIT ABRT PIPE TERM
fi

cp -a ${CUR_DIR}/debian-tests-data/* "${AUTOPKGTEST_TMP}"
cp -a ${CUR_DIR}/debian/tests/configuration.json "${AUTOPKGTEST_TMP}"

cd "${AUTOPKGTEST_TMP}"
ln -s /usr/share/orthanc/plugins/libOrthancWSI.so "${AUTOPKGTEST_TMP}"/libOrthancWSI.so

# Check if user 'orthanc' exists
if getent passwd orthanc > /dev/null 2>&1; then
    echo "User 'orthanc' exists."
else
	adduser --system --group orthanc
    echo "User 'orthanc' added."
fi


# Stop running instance of orthanc
sudo systemctl stop orthanc
sudo pkill -x Orthanc || true


# Start Orthanc, but not as a service to use the custom configuration (*)
# Use separate file descriptors than those of autopkgtest to avoid filling the pipe buffer
sudo /usr/sbin/Orthanc ./configuration.json --verbose > "${AUTOPKGTEST_TMP}/orthanc.log" 2>&1 &

# Try for 15 seconds to find the REST API of Orthanc in a healthy state
tries=15
set +e  # Thanks Etienne Mollier - https://lists.debian.org/debian-mentors/2025/04/msg00176.html
while true
do
    STATUSCODE=$(curl --silent --output /dev/null --write-out "%{http_code}" http://localhost:8042/system)
    test "$STATUSCODE" -eq 200 && echo "Orthanc initialized!" && break
    tries=$(expr "$tries" - 1)
    test "$tries" -le 0 && echo "Unable to initialize Orthanc" && exit 1
    sleep 1
done
set -e


# Transcode data and push to server
set +e  # Don't stop on errors
OrthancWSIDicomizer CMU-1-Small-Region.tiff --orthanc=http://localhost:8042
result=$?
set -e


# Stop Orthanc, which was not started as a service (*)
curl http://localhost:8042/tools/shutdown -X POST

count=0
while pgrep -x Orthanc > /dev/null; do
    pgrep -a Orthanc  # For debugging

    if [ "$count" -ge 60 ]; then
        echo "Orthanc still alive after 60s, sending SIGKILL" >&2
        sudo pkill -9 -x Orthanc || true
        break
    fi
    sleep 1
    count=$((count + 1))
done


# Check the result
if [ "$result" -eq 0 ]; then
    echo "TIFF transcoded and pushed to Orthanc server"
    exit 0
else
    echo "ERROR: TIFF was not correctly transcoded and pushed to Orthanc server, with $result"
    exit 1
fi
