#!/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 "fx_install removes the directories it created"
# The destination lies below directories that do not exist yet.  After the
# child exits, the file AND the new directories must be gone, but a directory
# that existed before (and the file next to the new ones) must stay.
mkdir "$T/preexisting"
cat >"$T/mkp.sh" <<SUB
. "$LIB/fixtures.sh"
fx_init
fx_install "$T/src" "$T/preexisting/new1/new2/file"
test -f "$T/preexisting/new1/new2/file"
SUB
sh "$T/mkp.sh"
[ -d "$T/preexisting" ] || fx_fail "pre-existing directory was removed"
[ ! -e "$T/preexisting/new1" ] || fx_fail "created directories not removed"

# ---------------------------------------------------------------------------
fx_step "fx_backup of a directory restores the whole tree"
# The child changes a file, adds one and deletes one inside a directory, and
# creates a second backup of a path that does not exist (must be removed).
mkdir "$T/dir"
echo keep >"$T/dir/keep"
echo gone >"$T/dir/deleted"
cat >"$T/dirbk.sh" <<SUB
. "$LIB/fixtures.sh"
fx_init
fx_backup "$T/dir"
fx_backup "$T/dir2"
echo changed >"$T/dir/keep"
echo extra >"$T/dir/extra"
rm "$T/dir/deleted"
mkdir "$T/dir2"
SUB
sh "$T/dirbk.sh"
[ "$(cat "$T/dir/keep")" = keep ] || fx_fail "changed file not restored"
[ "$(cat "$T/dir/deleted")" = gone ] || fx_fail "deleted file not restored"
[ ! -e "$T/dir/extra" ] || fx_fail "added file not removed"
[ ! -e "$T/dir/dir" ] || fx_fail "backup nested into directory"
[ ! -e "$T/dir2" ] || fx_fail "directory that did not exist was not removed"

# ---------------------------------------------------------------------------
fx_step "fx_edit: edits, restores, follows symlinks, refuses no-ops"
printf 'one\ntwo\n' >"$T/conf"
ln -s conf "$T/conf.link"
cat >"$T/edit.sh" <<SUB
. "$LIB/fixtures.sh"
fx_init
fx_edit "$T/conf.link" 's/^two\$/2/'
grep -qx 2 "$T/conf"
[ -L "$T/conf.link" ]
fx_edit "$T/conf" 's/^one\$/1/'
grep -qx 1 "$T/conf"
SUB
sh "$T/edit.sh"
[ "$(cat "$T/conf")" = "$(printf 'one\ntwo')" ] || fx_fail "fx_edit not reverted"
[ -L "$T/conf.link" ] || fx_fail "symlink was replaced"
# A script that matches nothing must fail, unless --allow-noop is given.
cat >"$T/noop.sh" <<SUB
. "$LIB/fixtures.sh"
fx_init
fx_edit --allow-noop "$T/conf" 's/nomatch/x/'
fx_edit "$T/conf" 's/nomatch/x/'
SUB
rc=0
sh "$T/noop.sh" 2>"$T/noop.err" || rc=$?
[ "$rc" -eq 1 ] || fx_fail "no-op fx_edit exit status $rc, expected 1"
fx_assert_contains "$T/noop.err" "did not change"

# ---------------------------------------------------------------------------
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_require reports missing programs and the package to add"
# The child shell asks for two programs that cannot exist.  It must exit with
# status 1 and name BOTH packages (all problems at once), the Depends: line
# and the control file; a program that is present must not be mentioned.
cat >"$T/req.sh" <<SUB
. "$LIB/fixtures.sh"
fx_require sh fx-no-such-prog:fx-pkg-one fx-no-such-two:fx-pkg-two
SUB
rc=0
sh "$T/req.sh" 2>"$T/req.err" || rc=$?
[ "$rc" -eq 1 ] || fx_fail "fx_require exit status $rc, expected 1"
fx_assert_contains "$T/req.err" "fx-no-such-prog (package: fx-pkg-one)" \
    "fx-no-such-two (package: fx-pkg-two)" \
    "Depends: fx-pkg-one, fx-pkg-two, @" "debian/tests/control"
grep -q 'sh (package' "$T/req.err" && fx_fail "fx_require complained about sh"
# Commands whose package is named differently are mapped by _fx_pkg_for.
[ "$(_fx_pkg_for ps)" = procps ] || fx_fail "ps should map to procps"
[ "$(_fx_pkg_for ldapsearch)" = ldap-utils ] || fx_fail "ldapsearch mapping"
[ "$(_fx_pkg_for socat)" = socat ] || fx_fail "default mapping"
# Success is silent and returns 0.
fx_require sh

# ---------------------------------------------------------------------------
fx_step "fx_log_mark / fx_log_expect / fx_log_absent"
L=$FX_LOGDIR/applog.log
echo "old: login ok" >"$L"
fx_log_expect applog "old: login"             # no mark: the whole file counts
fx_log_mark applog
echo "new: login failed" >>"$L"
fx_log_expect applog "login failed"
fx_log_absent -t 0 applog "login ok"          # logged before the mark: hidden
fx_log_mark applog                            # a new mark replaces the old one
fx_log_absent -t 0 applog "login failed"
# -n counts lines, -E is a regular expression, the default is a fixed string
printf 'hit 1\nhit 2\nhit 3\n' >>"$L"
fx_log_expect -n 3 applog "hit"
fx_log_expect -n 3 -E applog 'hit [0-9]$'
fx_log_expect -E applog 'hit (1|2)'
if ( fx_log_expect -t 0 -n 4 applog "hit" ) >/dev/null 2>&1; then
    fx_fail "-n 4 accepted with only three entries"
fi
if ( fx_log_expect -t 0 applog "hit [0-9]" ) >/dev/null 2>&1; then
    fx_fail "pattern was taken as a regular expression without -E"
fi
# The entry arrives after the action has returned: polling is needed.
fx_start slowlog sh -c 'sleep 1; echo "late entry"; exec sleep 300'
if ( fx_log_expect -t 0 slowlog "late entry" ) >/dev/null 2>&1; then
    fx_fail "entry was there at once; the test proves nothing"
fi
fx_log_expect slowlog "late entry"
fx_stop slowlog
# fx_log_absent asks the log for a barrier if it has one (the syslog module
# does), otherwise it waits.  A fake barrier proves the hook is used.
fx_log_barrier_hooked() { echo "$1" >"$FX_ROOT/barrier"; }
: >"$FX_LOGDIR/hooked.log"
fx_log_absent hooked anything
[ "$(cat "$FX_ROOT/barrier")" = 5 ] || fx_fail "barrier hook not called with the timeout"
fx_log_absent -t 2 hooked anything
[ "$(cat "$FX_ROOT/barrier")" = 2 ] || fx_fail "-t not passed to the barrier hook"
# A failing check shows the entries since the mark, and only those.
# log_fail_check COMMAND TEXT...: a child shell has "alpha", "beta" in the log
# svc, then a mark, then "gamma", and runs COMMAND, which must exit with
# status 1 and print every TEXT.
log_fail_check() {
    _lc=$1
    shift
    {
        printf '. "%s/fixtures.sh"\nfx_init\n' "$LIB"
        printf 'printf "alpha\\nbeta\\n" >"$FX_LOGDIR/svc.log"\n'
        printf 'fx_log_mark svc\nprintf "gamma\\n" >>"$FX_LOGDIR/svc.log"\n'
        printf '%s\n' "$_lc"
    } >"$T/lg.sh"
    rc=0
    sh "$T/lg.sh" >/dev/null 2>"$T/lg.err" || rc=$?
    [ "$rc" -eq 1 ] || fx_fail "'$_lc' exit status $rc, expected 1"
    for _w; do fx_assert_contains "$T/lg.err" "$_w"; done
    # a failing test also dumps every log file after a "====" line; the whole
    # svc.log is in there, so only look at what comes before
    if sed '/^====/,$d' "$T/lg.err" | grep -q alpha; then
        fx_fail "'$_lc': entries from before the mark were shown"
    fi
}
log_fail_check "fx_log_expect -t 0 svc beta" \
    "found on 0 line(s)" "| gamma" "expected log entry missing"
log_fail_check "fx_log_absent -t 0 svc gamma" \
    "unexpected entry" "| gamma" "unexpected log entry"
log_fail_check "fx_log_expect nosuch x" "no log 'nosuch'" "fx_start nosuch"
log_fail_check "fx_log_expect -n 0 svc x" "needs a positive"
log_fail_check "fx_log_expect -t abc svc x" "needs a number"
log_fail_check "fx_log_expect -Q svc x" "unknown option"
log_fail_check "fx_log_absent -n 2 svc x" "makes no sense"
log_fail_check "fx_log_expect svc" "usage"

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