#!/bin/bash

set -e

# GPG Key ID to use
GPG_KEY_ID="0F23ABFF8F00056D52F1A82E4A72C4B48B15B19F"

echo "Setting up GPG key for EveBox repository..."
echo "Using GPG key: $GPG_KEY_ID"

# Check if GPG is installed
if ! command -v gpg &> /dev/null; then
    echo "GPG is not installed. Installing..."
    sudo apt-get update
    sudo apt-get install -y gnupg
fi

# Check if the specified GPG key exists
if gpg --list-secret-keys "$GPG_KEY_ID" &> /dev/null; then
    echo "GPG key $GPG_KEY_ID found."

    # Export public key
    echo "Exporting public key..."
    gpg --armor --export "$GPG_KEY_ID" > evebox-repo.asc

    echo "Public key exported to evebox-repo.asc"
    echo ""
    echo "To add this repository to a client system, users should run:"
    echo "  wget -qO - https://your-repo-url/evebox-repo.asc | sudo apt-key add -"
    echo ""
    echo "GPG key setup complete!"
else
    echo "ERROR: GPG key $GPG_KEY_ID not found in your keyring!"
    echo ""
    echo "Please ensure the key is imported to your GPG keyring:"
    echo "  gpg --import your-private-key.asc"
    echo ""
    echo "Or if the key exists under a different user, you may need to:"
    echo "  sudo -u <user> gpg --export-secret-keys $GPG_KEY_ID | gpg --import"
    exit 1
fi