#!/bin/bash
set -euo pipefail

# Quick setup script for cloudnative-cr organization

ORG_NAME="cloudnative-cr"
TOKEN_PATH="${GITHUB_TOKEN_PATH:-$HOME/.github-token}"

echo "=== Peribolos Setup for cloudnative-cr ==="
echo ""

# Check for token
if [ ! -f "$TOKEN_PATH" ]; then
    echo "Step 1: Set up GitHub token"
    echo "----------------------------"
    echo "You need a GitHub personal access token with 'admin:org' scope."
    echo ""
    echo "1. Go to: https://github.com/settings/tokens/new"
    echo "2. Create a token with these scopes:"
    echo "   - admin:org (full control)"
    echo "   - repo (for private repos)"
    echo "3. Copy the token and run:"
    echo ""
    echo "   echo 'your-token-here' > ~/.github-token"
    echo "   chmod 600 ~/.github-token"
    echo ""
    exit 1
fi

echo "Token found at: $TOKEN_PATH"
echo ""

# Dump current configuration
echo "Step 2: Dumping current organization configuration..."
echo "------------------------------------------------------"
DUMP_FILE="config/org-dump-$(date +%Y%m%d-%H%M%S).yaml"

if go run k8s.io/test-infra/prow/cmd/peribolos@latest \
    --dump "$ORG_NAME" \
    --github-token-path "$TOKEN_PATH" \
    > "$DUMP_FILE" 2>&1; then
    echo "Configuration dumped to: $DUMP_FILE"
    echo ""

    echo "Step 3: Review the dumped configuration"
    echo "----------------------------------------"
    echo "The current state of your organization has been saved."
    echo "Review the file and use it to update config/org.yaml"
    echo ""
    echo "Commands:"
    echo "  cat $DUMP_FILE                    # View the dump"
    echo "  cp $DUMP_FILE config/org.yaml     # Use as base config"
    echo ""
    echo "Step 4: Edit config/org.yaml to define desired state"
    echo "-----------------------------------------------------"
    echo "Edit config/org.yaml with your desired organization structure."
    echo ""
    echo "Step 5: Apply configuration (dry-run first)"
    echo "--------------------------------------------"
    echo "  ./peribolos/apply.sh              # Dry-run (safe)"
    echo "  CONFIRM=true ./peribolos/apply.sh # Apply changes"
else
    echo "Error: Failed to dump organization configuration"
    echo ""
    echo "Possible issues:"
    echo "  - Token doesn't have admin:org permissions"
    echo "  - You're not an admin of the $ORG_NAME organization"
    echo "  - Network connectivity issues"
    echo ""
    echo "Verify your token permissions at:"
    echo "  https://github.com/settings/tokens"
    exit 1
fi
