#!/bin/sh
# Regression test for Debian bug #1121130:
#   "phpmyadmin postinst fails with exit status 10 when configuring
#    dbconfig-common (Debian 13 / trixie)"
#
# dbconfig-common is written to be sourced by maintainer scripts that do not run
# under "set -e": several of its debconf calls are deliberately unprotected and
# rely on its own error dialog. In debian/postinst and debian/prerm the code used
# to run under "set -e", so a debconf protocol error status -- 10 is "badparams",
# returned when the question or template does not exist (see
# Debconf::ConfModule.pm) -- aborted the maintainer script before
# dbconfig-common could report the problem. dpkg then left phpmyadmin in the "iF"
# (half-installed, removal failed) state, which breaks apt/dpkg.
#
# A server password policy (simple_password_check) is one way to reach that code
# path: the control-user password is rejected with ERROR 1819, and
# dbconfig-common tries to report it with an unprotected "db_subst" on its
# install-error template, which returns status 10 when that template was never
# registered for phpmyadmin.
#
# The missing-registration state is reproduced deterministically by hiding
# dbconfig-common's config hook while phpmyadmin is installed. That is the
# "gracefully exit and defer" situation dbconfig-common itself documents for a
# package configured before dbconfig-common is set up (see the comment in
# /usr/share/dbconfig-common/dpkg/config). The hook is restored afterwards.
#
# Assertions after the fix:
#  * scenario 1 (policy-violating password, dbconfig-common cannot register):
#    apt/dpkg complete, phpmyadmin is "ii" and absent from "dpkg --audit", and
#    the administrator is warned that the database setup failed;
#  * scenario 2 (no password policy, normal installation): the package installs
#    cleanly and the control user can connect.
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"
# 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/mariadb.sh"

AUTOPKGTEST_TMP=${AUTOPKGTEST_TMP:-/tmp/phpmyadmin-dep8}
mkdir -p "$AUTOPKGTEST_TMP"

PKG=phpmyadmin
CONFIG_HOOK="/usr/share/dbconfig-common/dpkg/config.mysql"
CONFIG_HOOK_SAVED="$AUTOPKGTEST_TMP/config.mysql.saved"
# mixed case + digits but no symbol: rejected by simple_password_check
WEAK_PASS="phpMyAdmin2026dbconfig"
# mixed case + digits + symbols: accepted by simple_password_check
STRONG_PASS="phpMyAdmin-2026!dbconfig"

dep8_require mariadb mariadb-install-db apt-get debconf-set-selections

preseed_dbconfig() {
    # With the config hook hidden the dbconfig-common questions do not exist yet;
    # dep8_preseed reports which ones it skipped instead of failing the test.
    dep8_preseed "$PKG" "$PKG/dbconfig-install" boolean true
    dep8_preseed "$PKG" "$PKG/database-type" select mysql
    dep8_preseed "$PKG" "$PKG/mysql/app-pass" password "$1"
    dep8_preseed "$PKG" "$PKG/app-password-confirm" password "$1"
    dep8_preseed "$PKG" "$PKG/reconfigure-webserver" multiselect ""
}

assert_fully_installed() {
    if ! dep8_assert_installed "$PKG"; then
        return 1
    fi
    if dpkg --audit | grep -q "$PKG"; then
        echo "--- dpkg --audit ---"
        dpkg --audit
        return 1
    fi
    return 0
}

cleanup() {
    if [ -e "$CONFIG_HOOK_SAVED" ]; then
        mv -f "$CONFIG_HOOK_SAVED" "$CONFIG_HOOK"
    fi
    dpkg --purge --force-all "$PKG" || true
    mariadb_system_sql -e "DROP DATABASE IF EXISTS phpmyadmin; DROP USER IF EXISTS 'phpmyadmin'@'localhost';" || true
    return 0
}
trap cleanup EXIT

# --- Start the database server and enforce a password policy -----------------
mariadb_start_system

echo "Enabling the server password policy (simple_password_check) ..."
if ! mariadb_system_sql -e "INSTALL SONAME 'simple_password_check';"; then
    dep8_fail "simple_password_check plugin not available"
fi

# Sanity check: the weak password must be rejected and the strong one accepted,
# otherwise the testbed does not enforce a policy and scenario 1 proves nothing.
if mariadb_system_sql -e "CREATE USER dep8weakprobe@localhost IDENTIFIED BY '${WEAK_PASS}';"; then
    mariadb_system_sql -e "DROP USER dep8weakprobe@localhost;" || true
    dep8_fail "the server did not enforce the expected password policy"
fi
if ! mariadb_system_sql -e "CREATE USER dep8strongprobe@localhost IDENTIFIED BY '${STRONG_PASS}';"; then
    dep8_fail "the policy-compliant test password was rejected by the server"
fi
mariadb_system_sql -e "DROP USER dep8strongprobe@localhost;" || true

# --- Scenario 1: a failing dbconfig-common must not break dpkg/apt ----------
echo "=== Scenario 1: policy-violating password, dbconfig-common not registered ==="
if [ ! -f "$CONFIG_HOOK" ]; then
    dep8_fail "$CONFIG_HOOK is not installed"
fi
mv "$CONFIG_HOOK" "$CONFIG_HOOK_SAVED"
preseed_dbconfig "$WEAK_PASS"

log1="$AUTOPKGTEST_TMP/install-weak.log"
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$PKG" \
    >>"$log1" 2>&1 || true

if ! assert_fully_installed; then
    echo "--- last 60 lines of $log1 ---"
    tail -60 "$log1"
    dep8_fail "$PKG was left half-configured after the dbconfig-common failure (bug #1121130)"
fi
if ! grep -q "WARNING: dbconfig-common failed to configure phpMyAdmin's database" "$log1"; then
    echo "--- last 60 lines of $log1 ---"
    tail -60 "$log1"
    dep8_fail "the administrator was not warned that the database configuration failed"
fi
echo "ok: package is fully installed and the database failure was reported"

# --- Scenario 2: a normal installation still works --------------------------
# The password policy is only needed by scenario 1. With it active, whether the
# user can be created depends on how dbconfig-common handles the password
# (dbc_dbpass is only set when the debconf question resolves, see the
# "db_get ... && dbc_dbpass=$RET" in /usr/share/dbconfig-common/dpkg/common),
# which is not what this test is about. Drop it and check the happy path.
echo "=== Scenario 2: normal installation, no password policy ==="
mariadb_system_sql -e "UNINSTALL SONAME 'simple_password_check';" || true
dpkg --purge --force-all "$PKG" || true
mv -f "$CONFIG_HOOK_SAVED" "$CONFIG_HOOK"
mariadb_system_sql -e "DROP DATABASE IF EXISTS phpmyadmin; DROP USER IF EXISTS 'phpmyadmin'@'localhost';" || true
preseed_dbconfig "$WEAK_PASS"

log2="$AUTOPKGTEST_TMP/install-normal.log"
if ! DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$PKG" >>"$log2" 2>&1; then
    echo "--- last 60 lines of $log2 ---"
    tail -60 "$log2"
    dep8_fail "clean installation failed"
fi
if ! assert_fully_installed; then
    echo "--- last 60 lines of $log2 ---"
    tail -60 "$log2"
    dep8_fail "$PKG is not fully installed after a clean installation"
fi
if grep -q "WARNING: dbconfig-common failed" "$log2"; then
    echo "--- last 60 lines of $log2 ---"
    tail -60 "$log2"
    dep8_fail "unexpected dbconfig-common failure during a clean installation"
fi
if [ ! -f /etc/phpmyadmin/config-db.php ]; then
    dep8_fail "/etc/phpmyadmin/config-db.php was not generated"
fi

# Use the password dbconfig-common actually stored rather than the one that was
# preseeded, so the check does not depend on how it generated it.
dbpass=$(sed -n "s/^.*\$dbpass *= *'\(.*\)';.*$/\1/p" /etc/phpmyadmin/config-db.php)
if [ -z "$dbpass" ]; then
    dep8_fail "no password found in /etc/phpmyadmin/config-db.php"
fi
if ! mariadb --no-defaults -u phpmyadmin -p"$dbpass" -e 'SELECT 1'; then
    echo "--- last 60 lines of $log2 ---"
    tail -60 "$log2"
    dep8_fail "the created control user cannot connect to the database"
fi
dep8_pass "clean installation works and the control user is functional"
