#!/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}🧪 Testing GPG with TTY environment variable...${NC}"

# Check if GPG files exist
if [ ! -f "sesterce-cli-private-key.gpg" ]; then
    echo -e "${RED}❌ Private key file not found. Run generate-gpg-key-no-agent.sh first.${NC}"
    exit 1
fi

# Create a temporary GPG home directory
TEMP_GNUPG=$(mktemp -d)
echo -e "${YELLOW}Using temporary GPG home: ${TEMP_GNUPG}${NC}"

# Set GPG home and TTY
export GNUPGHOME="$TEMP_GNUPG"
export GPG_TTY=$(tty)

echo -e "${YELLOW}GPG_TTY set to: $GPG_TTY${NC}"

# Create GPG configuration
mkdir -p "$TEMP_GNUPG"
cat > "$TEMP_GNUPG/gpg.conf" << EOF
# Disable GPG agent completely
no-use-agent
pinentry-mode loopback
EOF
chmod 600 "$TEMP_GNUPG/gpg.conf"

echo -e "${YELLOW}📋 GPG configuration:${NC}"
cat "$TEMP_GNUPG/gpg.conf"

# Import the private key
echo -e "${YELLOW}📥 Importing private key...${NC}"
gpg --batch --import sesterce-cli-private-key.gpg

# List imported keys
echo -e "${YELLOW}📋 Imported keys:${NC}"
gpg --list-secret-keys --keyid-format LONG

# 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 "${BLUE}Key ID: ${KEY_ID}${NC}"

# Test signing with passphrase
echo -e "${YELLOW}🧪 Testing signing...${NC}"
echo "test content" > test-file.txt

# Get passphrase from user
echo -e "${YELLOW}Enter the GPG passphrase:${NC}"
read -s GPG_PASSPHRASE
echo ""

# Test signing
if echo "$GPG_PASSPHRASE" | gpg --batch --yes --passphrase-fd 0 --sign test-file.txt; then
    echo -e "${GREEN}✅ Signing successful!${NC}"
    
    # Test verification
    if gpg --verify test-file.txt.gpg; then
        echo -e "${GREEN}✅ Verification successful!${NC}"
    else
        echo -e "${RED}❌ Verification failed!${NC}"
    fi
else
    echo -e "${RED}❌ Signing failed!${NC}"
fi

# Test APT repository signing
echo -e "${YELLOW}🧪 Testing APT repository signing...${NC}"
mkdir -p test-apt
echo "test release content" > test-apt/Release

if echo "$GPG_PASSPHRASE" | gpg --batch --yes --passphrase-fd 0 --clearsign -o test-apt/InRelease test-apt/Release; then
    echo -e "${GREEN}✅ APT repository signing successful!${NC}"
    echo -e "${YELLOW}📋 InRelease file created:${NC}"
    head -5 test-apt/InRelease
else
    echo -e "${RED}❌ APT repository signing failed!${NC}"
fi

# Clean up
rm -f test-file.txt test-file.txt.gpg
rm -rf test-apt
rm -rf "$TEMP_GNUPG"

echo -e "${GREEN}✅ GPG TTY test completed!${NC}" 