#!/bin/sh
# Check that the postinst empties /var/lib/phpmyadmin/tmp (#1054585).
#
# Everything the postinst prunes is disposable (the Twig cache below tmp/twig/,
# abandoned uploads), so all regular files must go, at any depth. The
# directories themselves and symlinks must survive, and a symlink must never
# make it delete its target outside the directory. The postinst is driven
# through dpkg-reconfigure so the real configure path runs and must still exit
# 0.
set -eu

# SC1091: the library path is computed at run time, so it cannot be
# followed statically. Its contents are checked on their own.
# shellcheck disable=SC1091
. "$(dirname "$0")/lib/helpers.sh"

PKG=phpmyadmin
TMP_DIR=/var/lib/phpmyadmin/tmp

[ -d "$TMP_DIR" ] || dep8_fail "$TMP_DIR does not exist"

# Unique names, so leftovers from an earlier run cannot mask a failure.
PREFIX="dep8-tmp-cleanup-$$"
OUTSIDE="$AUTOPKGTEST_TMP/$PREFIX-outside"
OLD="$TMP_DIR/$PREFIX-old"
RECENT="$TMP_DIR/$PREFIX-recent"
SESSION="$TMP_DIR/sess_$PREFIX"
SUBDIR="$TMP_DIR/$PREFIX-sub"
NESTED="$SUBDIR/nested"
LINK="$TMP_DIR/$PREFIX-link"

cleanup() {
    for _f in "$OUTSIDE" "$OLD" "$RECENT" "$SESSION" "$NESTED" "$LINK"; do
        if [ -e "$_f" ] || [ -L "$_f" ]; then
            rm "$_f"
        fi
    done
    if [ -d "$SUBDIR" ]; then
        # Not fatal: a leftover file here must not turn a passing run into a
        # failure, and "return 0" below would not be reached otherwise.
        rmdir "$SUBDIR" || true
    fi
    return 0
}
trap cleanup EXIT

echo "Planting files in $TMP_DIR ..."
echo outside >"$OUTSIDE"
: >"$OLD"
: >"$RECENT"
: >"$SESSION"
mkdir -p "$SUBDIR"
: >"$NESTED"
ln -s "$OUTSIDE" "$LINK"

# The age must not matter: the cleanup has no threshold. Set one of them in the
# past anyway, so a hidden age test in the implementation would be caught.
touch -d '2 days ago' "$OLD"

# Re-run the postinst without a database server or a webserver. The debconf
# questions dbconfig-common provides only exist once it managed to register
# them, so they are preseeded only when present; the postinst must cope with
# their absence and still reach the cleanup.
echo "Reconfiguring $PKG to run the postinst ..."
dep8_preseed "$PKG" "$PKG/dbconfig-install" boolean false
dep8_preseed "$PKG" "$PKG/reconfigure-webserver" multiselect ""
dpkg-reconfigure -f noninteractive "$PKG" || dep8_fail "dpkg-reconfigure $PKG failed"

[ ! -e "$OLD" ] || dep8_fail "temp file was not removed"
[ ! -e "$RECENT" ] || dep8_fail "recent temp file was not removed"
[ ! -e "$SESSION" ] || dep8_fail "session file was not removed"
[ ! -e "$NESTED" ] || dep8_fail "file in a subdirectory was not removed"
[ -d "$SUBDIR" ] || dep8_fail "subdirectory was removed"
[ -L "$LINK" ] || dep8_fail "symlink was removed"
[ -e "$OUTSIDE" ] || dep8_fail "symlink target outside $TMP_DIR was removed"
[ -d "$TMP_DIR" ] || dep8_fail "$TMP_DIR was removed"

dep8_pass "postinst emptied the directory, kept subdirectories and symlinks, and exited 0"
