#!/bin/bash
# setup-dev-environment.sh
# Sets up development environment for Crossplane provider development

set -euo pipefail

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

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

check_command() {
    local cmd=$1
    local install_cmd=$2
    
    if command -v "$cmd" &> /dev/null; then
        local version=$($cmd --version 2>/dev/null | head -1 || echo "installed")
        log "✓ $cmd is installed: $version"
        return 0
    else
        warn "$cmd is not installed"
        if [ -n "$install_cmd" ]; then
            info "Install with: $install_cmd"
        fi
        return 1
    fi
}

install_go() {
    log "Installing Go..."
    
    local go_version="1.21.5"
    local arch=$(uname -m)
    case "$arch" in
        x86_64) arch="amd64" ;;
        aarch64) arch="arm64" ;;
        *) error "Unsupported architecture: $arch" ;;
    esac
    
    local go_tar="go${go_version}.linux-${arch}.tar.gz"
    local go_url="https://go.dev/dl/${go_tar}"
    
    cd /tmp
    wget -q "$go_url"
    sudo rm -rf /usr/local/go
    sudo tar -C /usr/local -xzf "$go_tar"
    rm "$go_tar"
    
    # Add to PATH
    if ! grep -q "/usr/local/go/bin" ~/.bashrc 2>/dev/null; then
        echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
        export PATH=$PATH:/usr/local/go/bin
    fi
    
    log "✓ Go installed successfully"
}

install_kubectl() {
    log "Installing kubectl..."
    
    local kubectl_version=$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)
    curl -LO "https://storage.googleapis.com/kubernetes-release/release/${kubectl_version}/bin/linux/amd64/kubectl"
    chmod +x kubectl
    sudo mv kubectl /usr/local/bin/
    
    log "✓ kubectl installed successfully"
}

install_kind() {
    log "Installing kind (Kubernetes in Docker)..."
    
    curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.20.0/kind-linux-amd64
    chmod +x ./kind
    sudo mv ./kind /usr/local/bin/kind
    
    log "✓ kind installed successfully"
}

install_tools() {
    log "Installing development tools..."
    
    local tools=(
        "jq:apt-get install -y jq"
        "yq:snap install yq"
        "yamllint:pip3 install yamllint"
        "docker:apt-get install -y docker.io"
    )
    
    for tool_info in "${tools[@]}"; do
        IFS=':' read -r tool install_cmd <<< "$tool_info"
        if ! check_command "$tool" "$install_cmd"; then
            if [ "$tool" = "yq" ]; then
                # Alternative yq installation
                wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64
                chmod +x /usr/local/bin/yq
                log "✓ yq installed"
            elif [ "$tool" = "yamllint" ]; then
                pip3 install yamllint
                log "✓ yamllint installed"
            fi
        fi
    done
}

setup_git_hooks() {
    log "Setting up git hooks..."
    
    if [ -d ".git" ]; then
        mkdir -p .git/hooks
        
        cat > .git/hooks/pre-commit <<'EOF'
#!/bin/bash
# Pre-commit hook to validate configuration files

echo "Running pre-commit validation..."

if [ -f "./scripts/validate-configs.sh" ]; then
    ./scripts/validate-configs.sh
    if [ $? -ne 0 ]; then
        echo "❌ Configuration validation failed"
        exit 1
    fi
fi

echo "✓ Pre-commit checks passed"
EOF
        chmod +x .git/hooks/pre-commit
        log "✓ Git pre-commit hook installed"
    else
        warn "Not a git repository, skipping git hooks"
    fi
}

create_kind_cluster() {
    log "Creating kind cluster for local testing..."
    
    if command -v kind &> /dev/null; then
        if kind get clusters | grep -q "proxmox-test"; then
            warn "kind cluster 'proxmox-test' already exists"
        else
            kind create cluster --name proxmox-test --config - <<EOF
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
  extraPortMappings:
  - containerPort: 30000
    hostPort: 30000
    protocol: TCP
EOF
            log "✓ kind cluster 'proxmox-test' created"
        fi
    else
        warn "kind not installed, skipping cluster creation"
    fi
}

main() {
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║          Development Environment Setup                       ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    
    log "Checking development tools..."
    echo ""
    
    local missing_tools=0
    
    check_command "go" "See: https://go.dev/dl/" || { install_go; missing_tools=$((missing_tools + 1)); }
    check_command "kubectl" "See: https://kubernetes.io/docs/tasks/tools/" || { install_kubectl; }
    check_command "kind" "See: https://kind.sigs.k8s.io/" || { install_kind; }
    check_command "make" "apt-get install -y build-essential" || ((missing_tools++))
    check_command "docker" "apt-get install -y docker.io" || ((missing_tools++))
    
    echo ""
    install_tools
    echo ""
    
    setup_git_hooks
    echo ""
    
    read -p "Create kind cluster for local testing? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        create_kind_cluster
    fi
    
    echo ""
    log "Development environment setup complete!"
    echo ""
    info "Next steps:"
    info "1. cd crossplane-provider-proxmox"
    info "2. make build"
    info "3. make test"
    info "4. Start developing!"
}

main "$@"

