#!/usr/bin/sh
#
# pkg.post - post-install steps shared by alt-* packages (ALTEAPLN-107).
#
# Packages do not carry this logic themselves any more: alt-build-macros'
# %post_linksafe (rpm) and the packages' debian postinst only call this script,
# guarded by [ -x ], so a fix here reaches every installed package without a
# rebuild.
#
# Usage: pkg.post ACTION PACKAGE [--fresh] [--no-linksafe]
#   ACTION   post     the package's %post / postinst configure
#            trigger  the cloudlinux-solo-meta / cloudlinux-linksafe triggers
#            preun    the package's removal: rpm %preun with $1 = 0, deb
#                     prerm remove; not called on upgrades
#   PACKAGE  the (sub)package name, e.g. alt-php74-pecl-redis or
#            alt-python311-libs; on deb "$DPKG_MAINTSCRIPT_PACKAGE"
#   --fresh  a new installation, not an upgrade or reinstall: rpm %post with
#            $1 = 1, deb postinst configure with an empty $2
#   --no-linksafe  skip cl-linksafe-apply-group (Imunify builds, %__imunify)
#
# Steps:
#   1. cl-linksafe-apply-group PACKAGE                         (post, trigger)
#   2. alt-python*: the lve-stats alt-python trigger           (post)
#   3. alt-phpNN-*: the Plesk php.d step, see plesk_php_d()    (post)
#      or, on cPanel, the cPanel php.d step, see cpanel_php_d() (post --fresh)
#   4. alt-phpNN-* on cPanel: remove the php.d copy step 3 made,
#      see cpanel_php_d_remove()                                (preun)
#   5. Plesk: packagemng -sdf, see plesk_packagemng()          (post, preun)
#
# Never fails: a package transaction must not break on these steps.
#
# ALT_PHP_COMMON_ROOT prefixes every path; it exists for the tests only.

R="${ALT_PHP_COMMON_ROOT:-}"

usage() {
    echo "usage: $0 post|trigger|preun PACKAGE [--fresh] [--no-linksafe]" >&2
    exit 0
}

# php_d_name INI: the php.d name of a php.d.all ini. pdo and mysqlnd get the
# 20- names: pdo must load before the pdo_* drivers (ALTEAPLN-71). The ionCube
# loader must be the first zend_extension, so it gets 00-, as in php.d.std.
# Extensions other extensions load on get 40-, so they come before them:
# raphf and propro (http), apcu (apcu-bc's apc), psr (phalcon4/5).
php_d_name() {
    case "$1" in
        ioncube_loader.ini) echo 00-ioncube_loader.ini ;;
        mysqlnd.ini) echo 20-mysqlnd.ini ;;
        pdo.ini) echo 20-pdo.ini ;;
        apcu.ini|propro.ini|psr.ini|raphf.ini) echo "40-$1" ;;
        *) echo "$1" ;;
    esac
}

# by_php_d_name: sorts the php.d.all ini paths on stdin by their php.d name,
# the order PHP loads them in. A dependency's copy is then made before the
# copy of the ini that names it (40-raphf.ini before http.ini, whose
# raphf line would otherwise mark raphf as present).
by_php_d_name() {
    while IFS= read -r f; do
        printf '%s/%s\n' "$(php_d_name "$(basename "$f")")" "$f"
    done | LC_ALL=C sort | cut -d/ -f2-
}

# line_module LINE: the module an (zend_)extension line loads, active or
# commented; nothing for other lines
line_module() {
    m=$(printf '%s\n' "$1" | grep -E '^[[:space:];]*(zend_)?extension[[:space:]]*=' \
        | cut -d= -f2- | tr -d '"[:space:]')
    [ -n "$m" ] && basename "$m" .so
}

# ini_module INI: the module a php.d.all ini is for, its last extension line;
# the lines before it are dependencies
ini_module() {
    line_module "$(grep -E '^[[:space:];]*(zend_)?extension[[:space:]]*=' "$1" | tail -n 1)"
}

# php_d_has DIR MODULE: an ini in DIR mentions MODULE, active or commented
php_d_has() {
    grep -qsE "^[[:space:];]*(zend_)?extension[[:space:]]*=[[:space:]]*\"?([^\"[:space:]]*/)?$2([.]so)?\"?[[:space:]]*\$" \
        "$1"/*.ini
}

# pkg_files PACKAGE: the files PACKAGE installed, from the rpm or dpkg database
pkg_files() {
    if command -v rpm >/dev/null 2>&1 && rpm -q --quiet "$1" 2>/dev/null; then
        rpm -ql "$1"
    elif command -v dpkg-query >/dev/null 2>&1; then
        dpkg-query -L "$1" 2>/dev/null
    fi
}

# Plesk only lists the extensions that php.d declares, so an ini an alt-php
# package installs into php.d.all stays invisible to the panel (ALTEAPLN-78).
# On a Plesk host (/etc/plesk-release) where this alt-phpNN is registered as a
# handler, add each php.d.all ini that php.d does not have yet as a commented
# copy, the same layout the tuxcare-php migration produces, so the panel lists
# the extension as disabled and can enable it.
# Nothing in php.d is ever rewritten, renamed or removed: a file that exists
# is skipped, and so is a module that any php.d file already mentions (active
# or commented), so admin and panel choices and default.ini stay as they are.
# pdo_firebird/dblib/oci are left out, as the migration does.
plesk_php_d() {
    ver="$1"
    etc="$R/opt/alt/php$ver/etc"
    [ -f "$R/etc/plesk-release" ] || return 0
    grep -qs "\"alt-php$ver-" "$R/etc/psa/php_versions.json" || return 0
    d="$etc/php.d"
    [ -d "$d" ] || return 0
    for ini in "$etc"/php.d.all/*.ini; do
        [ -f "$ini" ] && printf '%s\n' "$ini"
    done | by_php_d_name |
    while IFS= read -r ini; do
        b=$(basename "$ini")
        case "$b" in
            pdo_firebird.ini|pdo_dblib.ini|pdo_oci.ini) continue ;;
        esac
        b=$(php_d_name "$b")
        { [ -e "$d/$b" ] || [ -L "$d/$b" ]; } && continue
        so=$(ini_module "$ini")
        [ -n "$so" ] || continue
        php_d_has "$d" "$so" && continue
        tmp="$d/.$b.pkgpost"
        sed -E 's/^[[:space:]]*(zend_)?extension[[:space:]]*=.*$/; &/' "$ini" > "$tmp" \
            && chmod 644 "$tmp" && mv -n "$tmp" "$d/$b"
        rm -f "$tmp"
    done
    return 0
}

# plesk_packagemng: on Plesk, mark the package list dirty so the panel reads
# the installed packages again, as the alt-phpNN packages do (ALTPHP-2177).
plesk_packagemng() {
    if [ -x "$R/usr/local/psa/admin/sbin/packagemng" ]; then
        "$R/usr/local/psa/admin/sbin/packagemng" -sdf >/dev/null 2>&1 || :
    fi
}

# cpanel_ini_copy INI MODULE [off] prints the copy: INI without the extension
# lines of other modules; with "off" the module's own line is commented out.
cpanel_ini_copy() {
    while IFS= read -r line || [ -n "$line" ]; do
        m=$(line_module "$line")
        [ -n "$m" ] && [ "$m" != "$2" ] && continue
        if [ -n "$m" ] && [ "${3:-}" = off ]; then
            printf '%s\n' "$line" | sed -E 's/^[[:space:]]*(zend_)?extension[[:space:]]*=.*$/; &/'
        else
            printf '%s\n' "$line"
        fi
    done < "$1"
}

# php_startup_errors VER DIR: the startup warnings and errors of alt-phpVER
# with DIR as its php.d, one per line, sorted; fails without a php binary
php_startup_errors() {
    php="$R/opt/alt/php$1/usr/bin/php"
    [ -x "$php" ] || return 1
    PHP_INI_SCAN_DIR="$2" "$php" -d display_errors=stderr -d display_startup_errors=1 \
        -d log_errors=0 -d html_errors=0 -m 2>&1 >/dev/null | grep -v '^[[:space:]]*$' | sort -u
    return 0
}

# cpanel_copy_loads VER DIR NAME COPY: COPY, added to DIR as NAME, brings no new
# startup warning or error. It is tried on a scratch copy of DIR, so php.d
# never holds a copy that breaks. Without a php binary there is nothing to
# try, and the copy counts as loading.
cpanel_copy_loads() {
    t=$(mktemp -d 2>/dev/null) || return 0
    for f in "$2"/*.ini; do
        [ -e "$f" ] && cp "$f" "$t/"
    done
    if before=$(php_startup_errors "$1" "$t"); then
        printf '%s\n' "$4" > "$t/$3"
        after=$(php_startup_errors "$1" "$t")
        rm -rf "$t"
        [ -z "$(printf '%s\n' "$after" | grep -vxF -e "$before" | grep -v '^$')" ]
        return
    fi
    rm -rf "$t"
    return 0
}

# cPanel wants the extension a new installation brings enabled in php.d. On a
# cPanel host (/usr/local/cpanel), a fresh install of an alt-phpNN package adds
# the php.d.all inis of that package only; upgrades and reinstalls add nothing.
# The Plesk rules hold: an existing file is skipped, and so is a module any
# php.d file mentions, active or commented, which leaves the core modules
# listed in default.ini to default.ini. The copy loads the module only: its
# dependency lines (igbinary and msgpack in redis.ini) are dropped, as the
# package's Requires / Depends bring the dependency packages, whose own fresh
# install adds their own inis.
# A copy that does not load on its own (a core module it needs is off in
# default.ini, a dependency's ini sorts after it, a library is missing) would
# warn on every PHP start, so it is added commented out instead, for the admin
# to enable.
cpanel_php_d() {
    ver="$1"
    pkg="$2"
    etc="$R/opt/alt/php$ver/etc"
    [ -x "$R/usr/local/cpanel" ] || return 0
    [ -f "$R/etc/plesk-release" ] && return 0
    d="$etc/php.d"
    [ -d "$d" ] || return 0
    pkg_files "$pkg" | grep -E "^/opt/alt/php$ver/etc/php[.]d[.]all/[^/]+[.]ini\$" |
    by_php_d_name |
    while IFS= read -r f; do
        ini="$R$f"
        [ -f "$ini" ] || continue
        b=$(php_d_name "$(basename "$ini")")
        { [ -e "$d/$b" ] || [ -L "$d/$b" ]; } && continue
        so=$(ini_module "$ini")
        [ -n "$so" ] || continue
        php_d_has "$d" "$so" && continue
        tmp="$d/.$b.pkgpost"
        copy=$(cpanel_ini_copy "$ini" "$so")
        cpanel_copy_loads "$ver" "$d" "$b" "$copy" || copy=$(cpanel_ini_copy "$ini" "$so" off)
        printf '%s\n' "$copy" > "$tmp" && chmod 644 "$tmp" && mv -n "$tmp" "$d/$b"
        rm -f "$tmp"
    done
    return 0
}

# On removal the cPanel copy goes with its package, or PHP would warn about the
# missing module on every start. A php.d file is removed only while it is
# still a copy cpanel_php_d() makes from the package's php.d.all ini, enabled
# or commented, which preun still has; a file the admin changed stays.
cpanel_php_d_remove() {
    ver="$1"
    pkg="$2"
    etc="$R/opt/alt/php$ver/etc"
    [ -x "$R/usr/local/cpanel" ] || return 0
    [ -f "$R/etc/plesk-release" ] && return 0
    d="$etc/php.d"
    [ -d "$d" ] || return 0
    pkg_files "$pkg" | grep -E "^/opt/alt/php$ver/etc/php[.]d[.]all/[^/]+[.]ini\$" |
    while IFS= read -r f; do
        ini="$R$f"
        [ -f "$ini" ] || continue
        b=$(php_d_name "$(basename "$ini")")
        [ -f "$d/$b" ] && [ ! -L "$d/$b" ] || continue
        so=$(ini_module "$ini")
        [ -n "$so" ] || continue
        cur=$(cat "$d/$b")
        if [ "$(cpanel_ini_copy "$ini" "$so")" = "$cur" ] ||
           [ "$(cpanel_ini_copy "$ini" "$so" off)" = "$cur" ]; then
            rm -f "$d/$b"
        fi
    done
    return 0
}

[ $# -ge 2 ] || usage
action="$1"
pkg="$2"
shift 2
linksafe=1
fresh=0
for arg in "$@"; do
    case "$arg" in
        --fresh) fresh=1 ;;
        --no-linksafe) linksafe=0 ;;
        *) usage ;;
    esac
done
[ -n "$pkg" ] || usage

case "$action" in
    post|trigger|preun) ;;
    *) usage ;;
esac

ver=$(expr "$pkg" : 'alt-php\([0-9][0-9]\)-')

if [ "$action" = preun ]; then
    if [ -n "$ver" ]; then
        cpanel_php_d_remove "$ver" "$pkg" || :
    fi
    plesk_packagemng
    exit 0
fi

if [ "$linksafe" = 1 ] && [ -x "$R/usr/bin/cl-linksafe-apply-group" ]; then
    "$R/usr/bin/cl-linksafe-apply-group" "$pkg" || :
fi

[ "$action" = post ] || exit 0

case "$pkg" in
    alt-python*)
        if [ -x "$R/usr/share/lve-stats/scriptlets/rpm_alt_python_trigger.sh" ]; then
            "$R/usr/share/lve-stats/scriptlets/rpm_alt_python_trigger.sh" || :
        fi
        ;;
esac

if [ -n "$ver" ]; then
    plesk_php_d "$ver" || :
    if [ "$fresh" = 1 ]; then
        cpanel_php_d "$ver" "$pkg" || :
    fi
fi

plesk_packagemng
exit 0
