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

    local key_file fingerprint
    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

        /usr/bin/pacman-key --lsign-key "$fingerprint"
    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
}
