#!/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 (no agent)...${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 for CI
mkdir -p ~/.gnupg
cat > ~/.gnupg/gpg.conf << EOF
# GPG configuration for CI environment
pinentry-mode loopback
EOF

chmod 600 ~/.gnupg/gpg.conf

# Create GPG batch file
cat > gpg-batch << EOF
%echo Generating GPG key for Sesterce CLI (CI environment)
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 (CI)
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 | head -1)

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}"
echo "$PASSPHRASE" | gpg --batch --yes --passphrase-fd 0 --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

# Test the key without agent
echo -e "${YELLOW}🧪 Testing key without agent...${NC}"
echo "test" > test-file.txt
echo "$PASSPHRASE" | gpg --batch --yes --passphrase-fd 0 --sign test-file.txt
echo "$PASSPHRASE" | gpg --batch --yes --passphrase-fd 0 --verify test-file.txt.gpg
rm test-file.txt test-file.txt.gpg

echo -e "${GREEN}✅ Key test successful!${NC}"

# 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. This key is configured for CI environments without GPG agent${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}" 