#!/bin/bash
# Build and push Crossplane provider
# DEPLOY-020: Build and deploy Crossplane provider

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PROVIDER_DIR="$PROJECT_ROOT/crossplane-provider-proxmox"

echo "=== Building Crossplane Provider ==="
echo ""

# Check if Go is installed
if ! command -v go &> /dev/null; then
    echo "✗ Go is not installed or not in PATH"
    echo "  Please install Go 1.21 or later"
    exit 1
fi

GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
echo "✓ Found Go $GO_VERSION"
echo ""

cd "$PROVIDER_DIR"

# Verify module path
echo "Verifying Go module..."
go mod verify
go mod tidy

# Generate code
echo ""
echo "Generating code and CRDs..."
make generate
make manifests

# Run tests
echo ""
echo "Running tests..."
make test || echo "⚠ Some tests failed, but continuing..."

# Build binary
echo ""
echo "Building provider binary..."
make build

# Build Docker image (if Docker is available)
if command -v docker &> /dev/null; then
    echo ""
    echo "Building Docker image..."
    IMG="${IMG:-ghcr.io/sankofa/crossplane-provider-proxmox:latest}"
    make docker-build IMG="$IMG"
    
    echo ""
    echo "✓ Docker image built: $IMG"
    echo ""
    echo "To push the image:"
    echo "  docker push $IMG"
    echo "  or"
    echo "  make docker-push IMG=$IMG"
else
    echo ""
    echo "⚠ Docker is not available, skipping Docker build"
    echo "  Binary built in: $PROVIDER_DIR/bin/provider"
fi

echo ""
echo "=== Build Complete ==="

