#!/bin/bash
# Script to set up GitHub web-based authentication

set -e

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "========================================="
log_info "GitHub Web Authentication Setup"
log_info "========================================="
log_info ""

# Check if GitHub CLI is installed
if ! command -v gh &> /dev/null; then
    log_warn "GitHub CLI (gh) is not installed"
    log_info "Installing GitHub CLI..."
    
    # Detect OS and install
    if command -v apt-get &> /dev/null; then
        log_info "Detected Debian/Ubuntu - installing via apt..."
        curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
        sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg
        echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
        sudo apt update
        sudo apt install gh -y
        log_success "GitHub CLI installed"
    elif command -v yum &> /dev/null; then
        log_info "Detected RHEL/CentOS - installing via yum..."
        sudo yum install gh -y
        log_success "GitHub CLI installed"
    else
        log_error "Could not detect package manager. Please install GitHub CLI manually:"
        log_info "Visit: https://cli.github.com/manual/installation"
        exit 1
    fi
else
    log_success "GitHub CLI is already installed"
    gh --version
fi

log_info ""
log_info "Authenticating with GitHub..."
log_info "This will open a web browser for authentication"
log_info ""

# Authenticate with GitHub (web-based)
if gh auth login; then
    log_success "Successfully authenticated with GitHub"
else
    log_error "Authentication failed"
    exit 1
fi

log_info ""
log_info "Configuring Git to use GitHub CLI for authentication..."
git config --global credential.helper ""
git config --global credential.helper store

# For HTTPS remotes, configure to use gh
log_info "Setting up credential helper for GitHub..."
gh auth setup-git

log_success "========================================="
log_success "Setup Complete!"
log_success "========================================="
log_info ""
log_info "You can now push to GitHub repositories"
log_info ""
log_info "Test with:"
log_info "  cd /home/intlc/projects/proxmox/pr-workspace/chains"
log_info "  git push origin update-chainid-138-rpc-endpoints"

