#!/usr/bin/bash -ef

log_error() {
  echo >&2 "Error: $1"
}

log_info() {
  echo >&2 "Info: $1"
}

if [ "$#" -lt 1 ]; then
    log_error "Missing the required path to the directory with trusted GPG keys."
    exit 1
elif [ "$#" -ge 2 ]; then
    log_error "Expected only one arguments, received $#. Possibly unescaped whitespaces? '$*'"
    exit 1
fi

USERSPACE_GPG_KEYS_DIR="$1"

if [ ! -e "$USERSPACE_GPG_KEYS_DIR" ]; then
    log_error "The $USERSPACE_GPG_KEYS_DIR directory does not exist."
    exit 1
fi

error_flag=0

while IFS= read -r -d '' key_file; do
    log_info "Importing GPG keys from: $key_file"

    if ! /usr/bin/rpmkeys --import --root /installroot "$key_file"; then
        error_flag=2
        log_error "Unable to import GPG keys: $key_file"
    fi
done < <(find -L "$USERSPACE_GPG_KEYS_DIR" -type f -print0)

exit $error_flag
