#!/bin/bash

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}🔑 Generating GPG key for CI environment...${NC}"

# Check if gpg is available
if ! command -v gpg &> /dev/null; then
    echo -e "${RED}❌ GPG is not installed. Please install GPG first.${NC}"
    exit 1
fi

# Generate a random passphrase
PASSPHRASE=$(openssl rand -base64 32)
echo -e "${YELLOW}Generated passphrase: ${PASSPHRASE}${NC}"

# Create GPG configuration file
cat > gpg-batch << EOF
%echo Generating GPG key for Sesterce CLI
Key-Type: RSA
Key-Length: 4096
Subkey-Type: RSA
Subkey-Length: 4096
Name-Real: Sesterce CLI
Name-Email: support@sesterce.com
Name-Comment: Debian Package Signing
Expire-Date: 0
Passphrase: ${PASSPHRASE}
%commit
%echo GPG key generation complete
EOF

# Generate the GPG key
echo -e "${YELLOW}🔑 Generating GPG key (this may take a moment)...${NC}"
gpg --batch --generate-key gpg-batch

# Get the key ID
KEY_ID=$(gpg --list-secret-keys --keyid-format LONG "Sesterce CLI" | grep "sec" | awk '{print $2}' | cut -d'/' -f2)

echo -e "${GREEN}✅ GPG key generated successfully!${NC}"
echo -e "${BLUE}Key ID: ${KEY_ID}${NC}"

# Export the private key
echo -e "${YELLOW}📤 Exporting private key...${NC}"
gpg --armor --export-secret-key "${KEY_ID}" > sesterce-cli-private-key.gpg

# Export the public key
echo -e "${YELLOW}📤 Exporting public key...${NC}"
gpg --armor --export "${KEY_ID}" > sesterce-cli-public-key.gpg

# Clean up
rm gpg-batch

echo -e "${GREEN}✅ GPG key generation complete!${NC}"
echo -e "${BLUE}📋 Next steps:${NC}"
echo -e "${YELLOW}1. Add the following secrets to your GitHub repository:${NC}"
echo -e "   GPG_PRIVATE_KEY:"
echo -e "   $(cat sesterce-cli-private-key.gpg)"
echo -e ""
echo -e "   GPG_PASSPHRASE:"
echo -e "   ${PASSPHRASE}"
echo -e ""
echo -e "${YELLOW}2. The public key is saved as: sesterce-cli-public-key.gpg${NC}"
echo -e "${YELLOW}3. You can use this public key for APT repository verification${NC}"
echo -e ""
echo -e "${RED}⚠️  IMPORTANT: Keep the private key and passphrase secure!${NC}"
echo -e "${RED}   Never commit these files to your repository.${NC}" 