#!/bin/sh
# =============================================================================
# autopkgtest "core": self-test of the autopkgtest-helper core library.
#
# Needs no root and no daemons beyond "sleep" and "sh".  It exercises the
# helpers that every other test builds on: quoting, templating, starting and
# stopping processes, waiting, reverting system files, teardown on failure and
# on signals, and certificate generation.
#
# HOW TO ADAPT THIS FILE
#  * Each "fx_step" block is independent; delete or copy blocks freely.
#  * Blocks that must observe teardown behaviour run a tiny script in a child
#    shell ("sh $T/....sh"), because teardown only happens when a shell exits.
#  * To run the test from a source checkout without installing the package:
#        FX_LIBDIR=$PWD/lib sh debian/tests/core
#  * Every failed check calls fx_fail, which exits 1 with a message; plain
#    command failures stop the test through "set -e".
# =============================================================================
set -eu

# Where the library lives.  Installed package: /usr/share/autopkgtest-helper.
# FX_LIBDIR lets a developer point the test at an uninstalled checkout.
LIB="${FX_LIBDIR:-/usr/share/autopkgtest-helper}"
export FX_LIBDIR="$LIB"
. "$LIB/fixtures.sh"

# Creates $FX_ROOT (a private temp dir) and installs the cleanup traps.
fx_init

# Scratch directory for this test's own files; removed together with FX_ROOT.
T=$FX_ROOT/selftest
mkdir "$T"

# ---------------------------------------------------------------------------
fx_step "fx_quote / fx_subst"
# fx_quote must produce something the shell can eval back to the same string,
# including embedded single quotes (used by fx_defer to store cleanup commands).
[ "$(fx_quote "it's")" = "'it'\\''s'" ] || fx_fail "fx_quote"
# fx_subst replaces @NAME@ by the value of $NAME.  The values deliberately
# contain the sed special characters | and & to prove they are escaped.
printf 'a=@A@ b=@B@\n' >"$T/in"
A='x|y&z' B=2 fx_subst "$T/in" "$T/out" A B
[ "$(cat "$T/out")" = 'a=x|y&z b=2' ] || fx_fail "fx_subst: $(cat "$T/out")"

# ---------------------------------------------------------------------------
fx_step "fx_start / fx_stop"
# "sleep 300" stands in for a well-behaved daemon that stays in the foreground.
fx_start sleeper sleep 300
fx_alive_name sleeper || fx_fail "sleeper not running"
pid=$(cat "$FX_RUNDIR/sleeper.pid")
fx_stop sleeper
fx_alive "$pid" && fx_fail "sleeper survived fx_stop"
[ ! -f "$FX_RUNDIR/sleeper.pid" ] || fx_fail "pidfile not removed"

# ---------------------------------------------------------------------------
fx_step "fx_stop escalates to SIGKILL"
# This "daemon" ignores SIGTERM, so fx_stop must wait and then use SIGKILL.
# The half second of sleep lets the shell install its trap before we stop it.
fx_start stubborn sh -c 'trap "" TERM; while :; do sleep 1; done'
sleep 0.5
pid=$(cat "$FX_RUNDIR/stubborn.pid")
fx_stop stubborn
fx_alive "$pid" && fx_fail "stubborn survived fx_stop"

# ---------------------------------------------------------------------------
fx_step "fx_wait_cmd"
# 1. A command that never succeeds must make fx_wait_cmd fail after the timeout.
fx_wait_cmd 1 false && fx_fail "fx_wait_cmd should time out"
# 2. A command that starts succeeding after a while must be waited for.
( sleep 1; touch "$T/appears" ) &
fx_wait_cmd 5 test -e "$T/appears" || fx_fail "fx_wait_cmd should have succeeded"
wait

# ---------------------------------------------------------------------------
fx_step "fx_install restores files at teardown"
# fx_install changes a file temporarily.  The child script below does the
# changes and exits; its teardown must put everything back.  Variables not
# escaped with a backslash are expanded NOW, by this shell, when the here
# document is written.
echo original >"$T/target"
echo new >"$T/src"
cat >"$T/sub.sh" <<SUB
. "$LIB/fixtures.sh"
fx_init
fx_install "$T/src" "$T/target" 600      # replaces an existing file
fx_install "$T/src" "$T/created"         # creates a file that did not exist
grep -q new "$T/target" && grep -q new "$T/created"
SUB
sh "$T/sub.sh"
[ "$(cat "$T/target")" = original ] || fx_fail "target not restored"
[ ! -e "$T/created" ] || fx_fail "created file not removed"

# ---------------------------------------------------------------------------
fx_step "teardown on failure: daemons killed, root removed, status kept"
# The child starts a daemon, writes a log line and then fails with "false"
# under "set -e".  We expect: exit status 1 preserved, daemon killed, temp
# directory gone and the log content printed to stderr for the user.
# Here, \$FX_ROOT etc. are escaped so that the CHILD expands them.
cat >"$T/fail.sh" <<SUB
set -e
. "$LIB/fixtures.sh"
fx_init
echo "\$FX_ROOT" >"$T/root"
fx_start victim sleep 300
cat "\$FX_RUNDIR/victim.pid" >"$T/victim.pid"
echo diagnostic-marker >"\$FX_LOGDIR/custom.log"
false
SUB
rc=0
sh "$T/fail.sh" 2>"$T/fail.err" || rc=$?
[ "$rc" -eq 1 ] || fx_fail "exit status $rc, expected 1"
fx_alive "$(cat "$T/victim.pid")" && fx_fail "daemon survived failed test"
[ ! -e "$(cat "$T/root")" ] || fx_fail "FX_ROOT not removed"
fx_assert_contains "$T/fail.err" "diagnostic-marker"

# ---------------------------------------------------------------------------
fx_step "teardown on SIGTERM"
# autopkgtest may kill a test that hangs.  The child sleeps forever in a loop;
# we send SIGTERM and expect its daemon to be cleaned up anyway.
cat >"$T/term.sh" <<SUB
. "$LIB/fixtures.sh"
fx_init
fx_start victim sleep 300
cat "\$FX_RUNDIR/victim.pid" >"$T/victim2.pid"
echo ready >"$T/ready"
while :; do sleep 1; done
SUB
sh "$T/term.sh" &
shpid=$!
fx_wait_cmd 5 test -e "$T/ready" || fx_fail "term.sh did not start"
kill -TERM "$shpid"
wait "$shpid" || true
fx_alive "$(cat "$T/victim2.pid")" && fx_fail "daemon survived SIGTERM of test"

# ---------------------------------------------------------------------------
fx_step "fx_cert"
# Create a certificate with explicit SANs and check that it chains to the CA.
fx_cert testhost DNS:testhost.example IP:192.0.2.1
openssl verify -CAfile "$FX_CA_CERT" "$FX_CERTDIR/testhost.crt"
openssl x509 -in "$FX_CERTDIR/testhost.crt" -noout -ext subjectAltName |
    grep -q 'testhost.example' || fx_fail "SAN missing"
# Default validity is 3 days: "-checkend N" succeeds only if the certificate
# is still valid N seconds from now.  Two days must pass, four must not.
openssl x509 -in "$FX_CERTDIR/testhost.crt" -noout -checkend $((2 * 86400)) >/dev/null ||
    fx_fail "certificate valid for less than 2 days"
openssl x509 -in "$FX_CERTDIR/testhost.crt" -noout -checkend $((4 * 86400)) >/dev/null &&
    fx_fail "certificate valid for more than 4 days"
# The CA gets one day more than the certificates it signs.
openssl x509 -in "$FX_CA_CERT" -noout -checkend $((3 * 86400 + 3600)) >/dev/null ||
    fx_fail "CA does not outlive the certificate"
# FX_CERT_DAYS overrides the default.  Variables set on the same line as a
# shell function call stay set after the call in some shells, so unset again.
FX_CERT_DAYS=10 fx_cert longlived
unset FX_CERT_DAYS || true
openssl x509 -in "$FX_CERTDIR/longlived.crt" -noout -checkend $((9 * 86400)) >/dev/null ||
    fx_fail "FX_CERT_DAYS not honoured"

# ---------------------------------------------------------------------------
fx_step "fx_free_port"
p=$(fx_free_port)
fx_is_listening "$p" && fx_fail "port $p reported in use"

echo "core: all tests passed"
