#!/bin/bash
# Citadel - Shared Script Utilities
# Sourced by other scripts for common functions

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

# Logging
log()     { echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*"; }
log_info()    { echo -e "${BLUE}[INFO]${NC} $1"; }
log_warn()    { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error()   { echo -e "${RED}[ERROR]${NC} $1" >&2; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
error()       { echo "[ERROR] $*" >&2; }

# Set default kubeconfig for K3s
export KUBECONFIG=${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}

# Prerequisite checks
require_kubectl() {
    if ! command -v kubectl &>/dev/null; then
        log_error "kubectl not found. Install K3s first (01-install-k3s.sh)."
        return 1
    fi
    if ! kubectl get nodes &>/dev/null; then
        log_error "Cannot connect to Kubernetes cluster."
        return 1
    fi
}

require_helm() {
    if ! command -v helm &>/dev/null; then
        log_error "helm not found. Install Cilium first (02-install-cilium.sh)."
        return 1
    fi
}

require_cilium() {
    if ! kubectl get pods -n kube-system -l k8s-app=cilium -o name 2>/dev/null | grep -q pod; then
        log_error "Cilium not found. Run 02-install-cilium.sh first."
        return 1
    fi
}

require_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "This script must be run as root."
        return 1
    fi
}

# Get the citadel repo root from any script location
get_repo_root() {
    local script_dir
    script_dir="$(cd "$(dirname "${BASH_SOURCE[1]}")" && pwd)"
    echo "$(dirname "$script_dir")"
}
