_install_onix_key() {
    if [[ ! -x /usr/bin/pacman-key || ! -d /usr/share/onix/keys ]]; then
        return 0
    fi

    local key_file fingerprint
    /usr/bin/pacman-key --init >/dev/null 2>&1 || true
    while IFS= read -r key_file; do
        fingerprint=$(/usr/bin/gpg --batch --show-keys --with-colons "$key_file" \
            | awk -F: '$1 == "fpr" { print $10; exit }')

        if [[ -z "$fingerprint" ]]; then
            echo "onix-base: invalid OpenPGP key: $key_file" >&2
            return 1
        fi

        if ! /usr/bin/pacman-key --list-keys "$fingerprint" >/dev/null 2>&1; then
            /usr/bin/pacman-key --add "$key_file"
        fi

        if ! /usr/bin/pacman-key --list-keys "$fingerprint" >/dev/null 2>&1; then
            echo "onix-base: key import failed: $fingerprint" >&2
            return 1
        fi

        # ISO profiles may not have a generated local signing key inside the
        # temporary mkarchiso root. Importing the public key is sufficient
        # for the profile's build-time SigLevel policy; signing is best effort.
        if /usr/bin/gpg --batch --list-secret-keys >/dev/null 2>&1; then
            /usr/bin/pacman-key --lsign-key "$fingerprint" >/dev/null 2>&1 || true
        fi
    done < <(find /usr/share/onix/keys -type f -name '*.key' -print)
}

_run_onix_system_fix() {
    local mode="${1:---transaction}"
    if [[ -x /usr/bin/onix-system-fix ]]; then
        /usr/bin/onix-system-fix "$mode" ||
            echo "onix-base: automatic system repair reported a non-fatal error" >&2
    fi
}

post_install() {
    _install_onix_key
    _run_onix_system_fix --first-install
}

post_upgrade() {
    _install_onix_key
    _run_onix_system_fix
}
