#!/usr/bin/env bash
###############################################################################
# verify-awx.sh — Verify AWX deployment status and access.
#
# Intended to run ON the target VM (tsys-awx.knel.net).
# Usage:  bash verify-awx.sh
###############################################################################
set -euo pipefail

export KUBECONFIG="${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}"

echo "=========================================================="
echo " AWX Deployment Verification — $(date)"
echo "=========================================================="

echo ""
echo "=== 1. k3s node ==="
kubectl get nodes

echo ""
echo "=== 2. AWX pods ==="
kubectl -n awx get pods

echo ""
echo "=== 3. AWX CR status ==="
kubectl -n awx get awx tsys-awx -o jsonpath='{range .status.conditions[*]}{.type}: {.message}{"\n"}{end}' 2>/dev/null || echo "AWX CR not found"

echo ""
echo "=== 4. Services ==="
kubectl -n awx get svc

echo ""
echo "=== 5. LoadBalancer / NodePort access ==="
LB_IP=$(kubectl -n awx get svc tsys-awx-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}' 2>/dev/null || echo "")
LB_HOST=$(kubectl -n awx get svc tsys-awx-service -o jsonpath='{.status.loadBalancer.ingress[0].hostname}' 2>/dev/null || echo "")
NODE_PORT=$(kubectl -n awx get svc tsys-awx-service -o jsonpath='{.spec.ports[0].nodePort}' 2>/dev/null || echo "")

if [ -n "${LB_IP}" ]; then
    echo "LoadBalancer IP: ${LB_IP}"
    ACCESS_URL="http://${LB_IP}"
elif [ -n "${LB_HOST}" ]; then
    echo "LoadBalancer hostname: ${LB_HOST}"
    ACCESS_URL="http://${LB_HOST}"
elif [ -n "${NODE_PORT}" ]; then
    echo "NodePort: ${NODE_PORT}"
    ACCESS_URL="http://$(hostname -I | awk '{print $1}'):${NODE_PORT}"
else
    echo "Service not ready yet"
    ACCESS_URL=""
fi

echo ""
echo "=== 6. Admin password ==="
ADMIN_PASS=$(kubectl -n awx get secret awx-admin-password -o jsonpath='{.data.password}' 2>/dev/null | base64 -d 2>/dev/null || echo "")
if [ -n "${ADMIN_PASS}" ]; then
    echo "User: admin"
    echo "Password: ${ADMIN_PASS}"
else
    echo "Admin password secret not found"
fi

echo ""
echo "=== 7. HTTP check ==="
if [ -n "${ACCESS_URL}" ]; then
    echo "Testing ${ACCESS_URL}..."
    HTTP_CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 "${ACCESS_URL}" 2>/dev/null || echo "failed")
    echo "HTTP response: ${HTTP_CODE}"
    if [ "${HTTP_CODE}" = "200" ] || [ "${HTTP_CODE}" = "302" ] || [ "${HTTP_CODE}" = "301" ]; then
        echo "✓ AWX is accessible at ${ACCESS_URL}"
    else
        echo "✗ AWX not yet responding (HTTP ${HTTP_CODE})"
    fi
fi

echo ""
echo "=========================================================="
if [ -n "${ACCESS_URL}" ]; then
    echo " AWX Access URL: ${ACCESS_URL}"
fi
echo "=========================================================="
