#!/usr/bin/env bash
###############################################################################
# deploy-awx.sh — Deploy AWX Operator + instance on k3s.
#
# Prerequisites: k3s must be installed and running (install-k3s.sh).
# Intended to run ON the target VM (tsys-awx.knel.net) as root or via sudo.
#
# Usage:  sudo bash deploy-awx.sh
###############################################################################
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export KUBECONFIG="${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}"

OPERATOR_VERSION="${OPERATOR_VERSION:-2.19.1}"

echo "=========================================================="
echo " AWX Operator deployment — version ${OPERATOR_VERSION}"
echo "=========================================================="

# ---------------------------------------------------------------------------
# Step 1: Create namespace
# ---------------------------------------------------------------------------
echo ""
echo "=== Step 1: Create namespace ==="
kubectl apply -f "${SCRIPT_DIR}/namespace.yaml"

# ---------------------------------------------------------------------------
# Step 2: Deploy AWX Operator
# ---------------------------------------------------------------------------
echo ""
echo "=== Step 2: Deploy AWX Operator ${OPERATOR_VERSION} ==="

# Clone the operator to get kustomize manifests
OPERATOR_DIR="/tmp/awx-operator-${OPERATOR_VERSION}"
rm -rf "${OPERATOR_DIR}"
git clone --branch "${OPERATOR_VERSION}" --depth 1 \
    "https://github.com/ansible/awx-operator.git" "${OPERATOR_DIR}" 2>&1 | tail -3

# The operator's default namespace is 'awx' — matches our setup
# Apply the operator via kustomize (config/default has the full manifest set)
kubectl apply -k "${OPERATOR_DIR}/config/default" 2>&1 || {
    echo "kustomize apply failed, trying raw manifests..."
    kubectl apply -f "https://raw.githubusercontent.com/ansible/awx-operator/${OPERATOR_VERSION}/deploy/awx-operator.yaml"
}

# Fix kube-rbac-proxy image (gcr.io/kubebuilder/kube-rbac-proxy was removed;
# quay.io/brancz/kube-rbac-proxy is the maintained replacement)
echo ""
echo "=== Patching kube-rbac-proxy image ==="
kubectl set image deployment/awx-operator-controller-manager -n awx \
    kube-rbac-proxy=quay.io/brancz/kube-rbac-proxy:v0.15.0 2>&1 || true

# Scale down any old replicasets that still reference the broken image
for rs in $(kubectl -n awx get rs -l control-plane=controller-manager -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null); do
    img=$(kubectl -n awx get rs "${rs}" -o jsonpath='{.spec.template.spec.containers[?(@.name=="kube-rbac-proxy")].image}' 2>/dev/null)
    if [[ "${img}" == *"gcr.io/kubebuilder"* ]]; then
        echo "Scaling down old RS ${rs} (has broken gcr.io image)"
        kubectl -n awx scale rs "${rs}" --replicas=0 2>&1
    fi
done

echo ""
echo "Waiting for AWX Operator deployment to be ready..."
kubectl -n awx wait --for=condition=Available deployment/awx-operator-controller-manager \
    --timeout=300s 2>&1 || {
    echo "Operator not ready yet — checking status..."
    kubectl -n awx get pods
}

# ---------------------------------------------------------------------------
# Step 3: Deploy AWX instance
# ---------------------------------------------------------------------------
echo ""
echo "=== Step 3: Deploy AWX instance ==="
kubectl apply -f "${SCRIPT_DIR}/awx-instance.yaml"

echo ""
echo "AWX instance created. Operator will now reconcile."
echo "This typically takes 5-10 minutes for the first deployment."
echo ""
echo "Monitor progress with:"
echo "  kubectl -n awx get awx tsys-awx -o jsonpath='{.status.conditions}' | jq ."
echo "  kubectl -n awx get pods -w"
echo "  kubectl -n awx logs deployment/awx-operator-controller-manager -f"
