#!/bin/sh
# Assert that the deterministic examples documented in basex(1) still work.
# Keep in sync with the EXAMPLES section of debian/man/basex.txt: every command
# below mirrors one shown there, so this test guards the manual against drift as
# upstream evolves the command/query syntax.
set -e

IN=/usr/share/doc/basex/examples/input.xml
export HOME="${AUTOPKGTEST_TMP:-/tmp}"
cd "$HOME"

n=0
check() {
	desc=$1; exp=$2; got=$3
	if [ "$got" = "$exp" ]; then
		echo "ok - $desc"; n=$((n + 1))
	else
		echo "FAIL - $desc: expected [$exp] got [$got]"; exit 1
	fi
}

# Script-mode evaluation.
check "arithmetic"          "42"                  "$(basex 19+23 2>/dev/null)"
check "element constructor" "<answer>42</answer>" "$(basex -q '<answer>{ 23+19 }</answer>' 2>/dev/null)"
check "query from stdin"    "42"                  "$(echo 19+23 | basex -q- 2>/dev/null)"

# Import into a database, then query it.
basex -c "CREATE DB input $IN" >/dev/null 2>&1
check "xpath on database"  "<li>Exercise 1</li>" "$(basex -c 'OPEN input; XQUERY //li[1]' 2>/dev/null)"
check "database as input"  "<li>Exercise 1</li>" "$(basex -i input -q '//li[1]' 2>/dev/null)"

# Query a file, writing the result to a file (-o must precede -q: options run in order).
basex -i "$IN" -o out.xml -q '//li[1]' 2>/dev/null
check "query to output file" "<li>Exercise 1</li>" "$(cat out.xml)"

# Execute commands from a script file.
printf 'create db cmddb <root/>\nlist\n' > commands.txt
if basex -C commands.txt 2>/dev/null | grep -q '^cmddb '; then
	echo "ok - command script"; n=$((n + 1))
else
	echo "FAIL - command script"; exit 1
fi

# HTML parsing (needs libtagsoup-java, pulled in via debian/tests/control).
printf '<html><ul><li>A<li>B</ul></html>\n' > bad.html
basex -c 'SET PARSER html' -c 'CREATE DB htmldb bad.html' >/dev/null 2>&1
want='<html><body><ul><li>A</li><li>B</li></ul></body></html>'
check "html parser (database)" "$want" "$(basex -q "doc('htmldb')" 2>/dev/null | tr -d ' \n')"
check "html parser (query)"    "$want" "$(basex -q 'fetch:doc("bad.html", map { "parser": "html" })' 2>/dev/null | tr -d ' \n')"

echo "all $n example checks passed"
