#!/usr/bin/env bash
# Redirect standard error to standard output since Calamares does not capture it.
exec 2>&1

set -u

CACHYOS_KEY_FILE="${CACHYOS_KEY_FILE:-/usr/share/calamares-advanced/modules/cachyos.asc}"
GPG_DIR="$(pacman-conf GPGDir 2>/dev/null || printf '%s\n' /etc/pacman.d/gnupg)"

cleanup_keyring_daemons() {
    gpgconf --homedir "$GPG_DIR" --kill all >/dev/null 2>&1 || true
}
trap cleanup_keyring_daemons EXIT

require_file() {
    local path="$1"
    [[ -r "$path" ]] || {
        echo "Required installer keyring file is missing: $path"
        exit 1
    }
}

pacman-key --init || exit 1
pacman-key --populate archlinux || exit 1
require_file "$CACHYOS_KEY_FILE"
pacman-key --add "$CACHYOS_KEY_FILE" || exit 1
pacman-key --lsign-key 882DCFE48E2051D48E2562ABF3B607488DB35A47 || exit 1
pacman-key --populate catos arch4edu archlinuxcn || exit 1
