#!/bin/bash
set -e

pkg=dicom3tools

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 /usr/share/doc/${pkg}/examples/* "${AUTOPKGTEST_TMP}"

cd "${AUTOPKGTEST_TMP}"

echo -e "\e[93m\e[1mChecking installed commands\e[0m"

# Every command that the package is expected to ship must actually be
# installed; a build that silently loses one must not pass the test.
for cmd in andump dcdirdmp dcdump dcentvfy dcfile dchist dciodvfy dckey \
	dcposn dcsort dcsrdump dcstats dctable dctable_decompressingprn \
	dctopgm8 dctopgx dctopnm dcunrgb jpegdump; do
	if ! command -v "${cmd}" >/dev/null 2>&1; then
		echo -e "\e[91m\e[1mFAIL: ${cmd} is not installed\e[0m" >&2
		exit 1
	fi
done

echo -e "\e[92m\e[1mPASS\e[0m"

echo -e "\e[93m\e[1mRunning Tests\e[0m"

dcfile 0051.dcm

echo -e "\e[92m\e[1mPASS\e[0m"

dciodvfy 0051.dcm

echo -e "\e[92m\e[1mPASS\e[0m"

dcdump 0051.dcm

echo -e "\e[92m\e[1mPASS\e[0m"

echo -e "\e[93m\e[1mRunning regression tests\e[0m"

if dciodvfy jpeg2000part2.dcm 2>&1 | grep -q "Undefined value length of other byte/word element"; then
	echo -e "\e[91m\e[1mFAIL: JPEG 2000 Part 2 transfer syntax not recognized\e[0m" >&2
	exit 1
fi

if dciodvfy us-retired.dcm 2>&1 | grep -q "Information Object Not found"; then
	echo -e "\e[91m\e[1mFAIL: retired Ultrasound Multiframe SOP Class not recognized\e[0m" >&2
	exit 1
fi

if dcdump command-group-length.dcm 2>&1 | grep -q "Tags out of order"; then
	echo -e "\e[91m\e[1mFAIL: leading (0000,0000) element rejected\e[0m" >&2
	exit 1
fi

if dciodvfy pixeldata32.dcm 2>&1 | grep -q "Assertion"; then
	echo -e "\e[91m\e[1mFAIL: 32-bit Pixel Data aborts dciodvfy\e[0m" >&2
	exit 1
fi

if ! dcdump pixeldata32.dcm >/dev/null 2>&1; then
	echo -e "\e[91m\e[1mFAIL: 32-bit Pixel Data cannot be dumped\e[0m" >&2
	exit 1
fi

echo -e "\e[92m\e[1mPASS\e[0m"
