#!/bin/sh
# Start ldap-rest with the "static" plugin and check that the JSON schemas
# installed in /usr/share/ldap-rest/static are really served.
set -e

TMP="${AUTOPKGTEST_TMP:-/tmp}"
LOG="$TMP/ldap-rest.log"
BODY="$TMP/body"

# Compatibility symlink for code resolving "static" from the module directory
test -L /usr/share/nodejs/ldap-rest/static
test "$(readlink -f /usr/share/nodejs/ldap-rest/static)" = /usr/share/ldap-rest/static
echo "OK: /usr/share/nodejs/ldap-rest/static -> /usr/share/ldap-rest/static"

# Defaults compiled into the package must point inside the served tree
for option in --schemas-path --static-path --group-schema; do
	path=$(node -e 'import("/usr/share/nodejs/ldap-rest/dist/config/args.js").then((m) => process.stdout.write(m.default.find((a) => a[0] === process.argv[1])[2]))' -- "$option")
	case "$path" in
	/usr/share/ldap-rest/static*) ;;
	*)
		echo "$option default is outside the served tree: $path" >&2
		exit 1
		;;
	esac
	test -e "$path"
	echo "OK: $option -> $path"
done

# Let the kernel pick the port: a fixed one would collide with whatever else
# runs on the CI machine
free_port() {
	node -e 'const probe = require("net").createServer();
probe.listen(0, "127.0.0.1", () => {
  const { port } = probe.address();
  probe.close(() => console.log(port));
});'
}

start_server() {
	port=$(free_port)
	url="http://127.0.0.1:$port"
	ldap-rest --plugin core/static --port "$port" >"$LOG" 2>&1 &
	server=$!
	i=0
	until curl -sf "$url/static/schemas/twake/groups.json" -o /dev/null; do
		# the port may have been taken between the probe and the bind
		kill -0 $server 2>/dev/null || return 1
		i=$((i + 1))
		if [ $i -gt 30 ]; then
			echo "server did not answer on port $port" >&2
			cat "$LOG" >&2
			exit 1
		fi
		sleep 1
	done
	echo "OK: server listening on port $port"
}

server=
trap 'kill $server 2>/dev/null || true' EXIT

attempt=1
until start_server; do
	attempt=$((attempt + 1))
	if [ $attempt -gt 3 ]; then
		echo "server never managed to bind a port" >&2
		cat "$LOG" >&2
		exit 1
	fi
done

check() {
	code=$(curl -s -o "$BODY" -w '%{http_code}' "$url$1")
	if [ "$code" != "$2" ]; then
		echo "GET $1: got $code, expected $2" >&2
		exit 1
	fi
	echo "OK: GET $1 -> $code"
}

check /static/schemas/twake/groups.json 200
node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' -- "$BODY"
echo "OK: served schema is valid JSON"
# schema reached through a relative symlink inside the schemas tree
check /static/schemas/twake/devices.json 200
check /static/schemas/standard/users.json 200
check /static/schemas/does-not-exist.json 404
# --static-path must not give access to /usr/share/ldap-rest/bin
check /static/bin/sync-james 404

echo "All checks passed"
