_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)
}

post_install() {
    _install_onix_key
}

post_upgrade() {
    _install_onix_key
}
