#!/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}🔐 Adding GPG secrets to GitHub repository...${NC}"

# Check if 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

if [ ! -f "sesterce-cli-public-key.gpg" ]; then
    echo -e "${RED}❌ Public key file not found. Run generate-gpg-key-no-agent.sh first.${NC}"
    exit 1
fi

# Get repository info
if [ ! -d ".git" ]; then
    echo -e "${RED}❌ Not in a git repository${NC}"
    exit 1
fi

REPO_URL=$(git remote get-url origin)
if [[ $REPO_URL == *"github.com"* ]]; then
    # Extract owner/repo from git URL
    if [[ $REPO_URL == *"git@github.com:"* ]]; then
        REPO_PATH=$(echo $REPO_URL | sed 's/git@github.com://' | sed 's/\.git$//')
    elif [[ $REPO_URL == *"https://github.com/"* ]]; then
        REPO_PATH=$(echo $REPO_URL | sed 's/https:\/\/github.com\///' | sed 's/\.git$//')
    else
        echo -e "${RED}❌ Could not parse GitHub repository URL${NC}"
        exit 1
    fi
    
    echo -e "${YELLOW}Repository: ${REPO_PATH}${NC}"
else
    echo -e "${RED}❌ Not a GitHub repository${NC}"
    exit 1
fi

# Check if gh CLI is available
if ! command -v gh &> /dev/null; then
    echo -e "${YELLOW}⚠️  GitHub CLI (gh) not found. Manual steps required.${NC}"
    echo -e "${BLUE}📋 Manual steps to add secrets:${NC}"
    echo -e "${YELLOW}1. Go to: https://github.com/${REPO_PATH}/settings/secrets/actions${NC}"
    echo -e "${YELLOW}2. Add these secrets:${NC}"
    echo -e ""
    echo -e "${GREEN}GPG_PRIVATE_KEY:${NC}"
    cat sesterce-cli-private-key.gpg
    echo -e ""
    echo -e "${GREEN}GPG_PASSPHRASE:${NC}"
    # Extract passphrase from the script output or generate a new one
    echo -e "${YELLOW}Use the passphrase from the generate-gpg-key-no-agent.sh output${NC}"
    exit 0
fi

# Check if user is authenticated
if ! gh auth status &> /dev/null; then
    echo -e "${RED}❌ Not authenticated with GitHub CLI. Run 'gh auth login' first.${NC}"
    exit 1
fi

# Get the passphrase (you'll need to provide this)
echo -e "${YELLOW}Enter the GPG passphrase (from generate-gpg-key-no-agent.sh output):${NC}"
read -s GPG_PASSPHRASE
echo ""

# Add the secrets
echo -e "${YELLOW}Adding GPG_PRIVATE_KEY secret...${NC}"
gh secret set GPG_PRIVATE_KEY --repo "${REPO_PATH}" --body-file sesterce-cli-private-key.gpg

echo -e "${YELLOW}Adding GPG_PASSPHRASE secret...${NC}"
echo "$GPG_PASSPHRASE" | gh secret set GPG_PASSPHRASE --repo "${REPO_PATH}"

echo -e "${GREEN}✅ GPG secrets added successfully!${NC}"
echo -e "${BLUE}📋 Next steps:${NC}"
echo -e "${YELLOW}1. The workflow will now use GPG signing for APT repository${NC}"
echo -e "${YELLOW}2. Public key is available at: sesterce-cli-public-key.gpg${NC}"
echo -e "${YELLOW}3. You can share the public key for APT repository verification${NC}" 