#!/bin/bash
# GitHub Actions Permission Setup Script
# This script ensures proper permissions for CI/CD operations

set -e

echo "🔧 Setting up GitHub Actions permissions..."

# Check if we're running in GitHub Actions
if [ "${GITHUB_ACTIONS:-false}" = "true" ]; then
    echo "📋 Running in GitHub Actions environment"
    echo "   Runner: ${RUNNER_NAME:-unknown}"
    echo "   Workspace: ${GITHUB_WORKSPACE:-unknown}"
    echo "   User: $(whoami)"
    echo "   UID/GID: $(id -u)/$(id -g)"

    WORKSPACE="${GITHUB_WORKSPACE:-$(pwd)}"
else
    echo "📋 Running in local development environment"
    WORKSPACE="$(pwd)"
fi

echo "📁 Working in: $WORKSPACE"

# Function to safely create directories with proper permissions
create_output_dirs() {
    echo "📁 Creating output directories..."

    # Create directories that MCP servers need
    local dirs=(
        "$WORKSPACE/outputs"
    )

    for dir in "${dirs[@]}"; do
        if [ ! -d "$dir" ]; then
            echo "   Creating: $dir"
            mkdir -p "$dir" || {
                echo "⚠️  Warning: Could not create $dir"
                continue
            }
        fi

        # Ensure proper permissions
        chmod 755 "$dir" 2>/dev/null || {
            echo "⚠️  Warning: Could not set permissions on $dir"
        }
    done
}

# Function to clean up problematic files
cleanup_problematic_files() {
    echo "🗑️ Cleaning up problematic files..."

    # Remove Python cache that might have permission issues
    find "$WORKSPACE" -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
    find "$WORKSPACE" -type d -name ".pytest_cache" -exec rm -rf {} + 2>/dev/null || true
    find "$WORKSPACE" -type f -name "*.pyc" -delete 2>/dev/null || true

    # Remove any existing output files that might have wrong permissions
    find "$WORKSPACE/outputs" -type f 2>/dev/null | head -10 | while read -r file; do
        if [ ! -w "$file" ]; then
            echo "   Removing file with bad permissions: $file"
            rm -f "$file" 2>/dev/null || true
        fi
    done
}

# Function to set up Docker environment variables
setup_docker_env() {
    echo "🐳 Setting up Docker environment..."

    # Set USER_ID and GROUP_ID for docker-compose
    export USER_ID
    USER_ID=$(id -u)
    export GROUP_ID
    GROUP_ID=$(id -g)

    echo "   USER_ID: $USER_ID"
    echo "   GROUP_ID: $GROUP_ID"

    # Create .env file for docker-compose
    cat > "$WORKSPACE/.env" << EOF
# Docker user permissions
USER_ID=$USER_ID
GROUP_ID=$GROUP_ID

# Generated by setup-github-actions-permissions.sh
# This ensures containers run with proper user permissions
EOF

    echo "✅ Created .env file with user permissions"
}

# Function to test Docker permissions
test_docker_permissions() {
    echo "🧪 Testing Docker permissions..."

    # Check if docker-compose is available
    if ! command -v docker-compose &> /dev/null; then
        echo "⚠️  docker-compose not found, skipping permission test"
        return 0
    fi

    # Test creating a simple container with the user permissions
    if docker-compose run --rm python-ci bash -c "whoami && id && touch /tmp/test-permission && ls -la /tmp/test-permission" 2>/dev/null; then
        echo "✅ Docker user permissions working correctly"
    else
        echo "⚠️  Docker permission test failed - this may cause issues"
    fi
}

# Function to set up git safe directories
setup_git_safety() {
    echo "🔐 Setting up git safe directories..."

    # Add workspace to git safe directories
    git config --global --add safe.directory "$WORKSPACE" 2>/dev/null || true

    # Also add common paths that might be used
    git config --global --add safe.directory "$WORKSPACE/template-repo" 2>/dev/null || true

    echo "✅ Git safe directories configured"
}

# Main execution
main() {
    echo "🚀 Starting permission setup..."
    echo ""

    create_output_dirs
    echo ""

    cleanup_problematic_files
    echo ""

    setup_docker_env
    echo ""

    setup_git_safety
    echo ""

    # Only test Docker in local environment or if Docker is available
    if [ "${GITHUB_ACTIONS:-false}" != "true" ] || command -v docker-compose &> /dev/null; then
        test_docker_permissions
        echo ""
    fi

    echo "✅ Permission setup complete!"
    echo ""
    echo "📌 Summary:"
    echo "   - Output directories created with proper permissions"
    echo "   - Problematic cache files removed"
    echo "   - Docker user environment configured"
    echo "   - Git safe directories set up"
    echo ""
    echo "📌 Next steps:"
    echo "   - Docker containers will now run with USER_ID=$USER_ID"
    echo "   - Named volumes will be used to avoid local permission conflicts"
    echo "   - Output files should be accessible without permission issues"
}

# Run the main function
main
