#!/bin/bash
# Quick script to check SSH configuration for GitLab

echo "🔍 Checking SSH configuration for GitLab..."
echo "=========================================="

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Check for SSH keys
echo -e "\n📁 Checking for SSH keys..."
SSH_KEYS_FOUND=false

for key_type in "ed25519" "rsa" "ecdsa"; do
    if [ -f "$HOME/.ssh/id_${key_type}" ]; then
        echo -e "${GREEN}✅ Found ${key_type} key: ~/.ssh/id_${key_type}${NC}"
        SSH_KEYS_FOUND=true
    fi
done

if [ "$SSH_KEYS_FOUND" = false ]; then
    echo -e "${RED}❌ No SSH keys found${NC}"
    echo -e "${YELLOW}To generate a new SSH key, run:${NC}"
    echo "  ssh-keygen -t ed25519 -C 'your-email@example.com'"
    exit 1
fi

# Check SSH agent
echo -e "\n🔐 Checking SSH agent..."
if ssh-add -l &>/dev/null; then
    echo -e "${GREEN}✅ SSH agent is running with keys loaded${NC}"
    ssh-add -l | sed 's/^/  /'
else
    if [ $? -eq 2 ]; then
        echo -e "${YELLOW}⚠️  SSH agent not running${NC}"
        echo "  Start it with: eval \"\$(ssh-agent -s)\""
        echo "  Then add your key: ssh-add ~/.ssh/id_ed25519"
    else
        echo -e "${YELLOW}⚠️  SSH agent running but no keys loaded${NC}"
        echo "  Add your key with: ssh-add ~/.ssh/id_ed25519"
    fi
fi

# Test GitLab connection
echo -e "\n🌐 Testing GitLab SSH connection..."
ssh -T git@gitlab.com 2>&1 | {
    while IFS= read -r line; do
        if [[ "$line" == *"Welcome to GitLab"* ]]; then
            echo -e "${GREEN}✅ GitLab SSH authentication successful!${NC}"
            echo "  $line"
            CONNECTION_OK=true
        elif [[ "$line" == *"Permission denied"* ]]; then
            echo -e "${RED}❌ GitLab SSH authentication failed${NC}"
            echo -e "${YELLOW}Your SSH key may not be added to GitLab${NC}"
            echo "  1. Copy your public key: cat ~/.ssh/id_ed25519.pub"
            echo "  2. Add it here: https://gitlab.com/-/profile/keys"
            CONNECTION_OK=false
        fi
    done
    
    if [ "$CONNECTION_OK" = true ]; then
        echo -e "\n${GREEN}🎉 You're all set! SSH is properly configured for GitLab${NC}"
        echo -e "\nYou can now:"
        echo "  • Use git with SSH URLs: git@gitlab.com:username/repo.git"
        echo "  • Run pg-api scripts with automatic SSH detection"
        exit 0
    else
        exit 1
    fi
}

exit $?