#!/bin/sh

pkg=orthanc-python
service_name=orthanc
CUR_DIR=`pwd`
export LC_ALL=C.UTF-8
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/rest.py "${AUTOPKGTEST_TMP}"
cp -a ${CUR_DIR}/debian/tests/configuration.json "${AUTOPKGTEST_TMP}"

cp -a /usr/share/doc/${pkg}/ "${AUTOPKGTEST_TMP}"

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


echo "Running Tests"

# 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 Orthanc

sudo /usr/sbin/Orthanc ./configuration.json --verbose &

# Try for 15 times to find orthanc process otherwise exit
tries=15
while true
do
	sh -c "pgrep -ax Orthanc" 2>&1
	test "$?" -eq 0 && echo "Orthanc initialized!" && break
	tries=$(expr "$tries" - 1)
	test "$tries" -le 0 && echo "Unable to initialize Orthanc" && exit 1
	sleep 1
done

# Use curl to hit the REST API endpoint
result=$(curl -s http://localhost:8042/toto)

# Stop orthanc
sudo systemctl stop orthanc
sudo pkill Orthanc

# Check the result
if [ "$result" = "ok" ]; then
    echo "Test passed"
    exit 0
else
    echo "Test failed with $result"
    exit 1
fi
