#!/bin/bash
set -euo pipefail

# Control Plane Components Installation Script

GITOPS_REPO="${GITOPS_REPO:-https://github.com/yourorg/hybrid-cloud-gitops}"
GITOPS_BRANCH="${GITOPS_BRANCH:-main}"
ARGOCD_NAMESPACE="${ARGOCD_NAMESPACE:-argocd}"

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" >&2
}

error() {
    log "ERROR: $*"
    exit 1
}

check_prerequisites() {
    log "Checking prerequisites..."
    
    if ! command -v kubectl &> /dev/null; then
        error "kubectl is not installed"
    fi
    
    if ! kubectl cluster-info &> /dev/null; then
        error "Cannot connect to Kubernetes cluster"
    fi
}

install_argocd() {
    log "Installing ArgoCD..."
    
    kubectl create namespace ${ARGOCD_NAMESPACE} --dry-run=client -o yaml | kubectl apply -f -
    
    kubectl apply -n ${ARGOCD_NAMESPACE} -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
    
    log "Waiting for ArgoCD to be ready..."
    kubectl wait --for=condition=available deployment/argocd-server -n ${ARGOCD_NAMESPACE} --timeout=600s
    
    # Get initial admin password
    ARGOCD_PASSWORD=$(kubectl -n ${ARGOCD_NAMESPACE} get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d)
    log "ArgoCD admin password: ${ARGOCD_PASSWORD}"
    log "Save this password securely!"
}

install_argocd_applications() {
    log "Installing ArgoCD applications from GitOps repo..."
    
    # Apply root application
    kubectl apply -f - <<EOF
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: root-apps
  namespace: ${ARGOCD_NAMESPACE}
spec:
  project: default
  source:
    repoURL: ${GITOPS_REPO}
    targetRevision: ${GITOPS_BRANCH}
    path: gitops/apps
  destination:
    server: https://kubernetes.default.svc
    namespace: ${ARGOCD_NAMESPACE}
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true
EOF
    
    log "ArgoCD applications will sync automatically from GitOps repo"
}

install_crossplane_provider() {
    log "Installing Crossplane Proxmox provider..."
    
    # Install CRDs
    if [ -d "../crossplane-provider-proxmox/config/crd/bases" ]; then
        kubectl apply -f ../crossplane-provider-proxmox/config/crd/bases/
    else
        log "Warning: Crossplane provider CRDs not found, skipping..."
    fi
    
    # Install provider
    if [ -f "../crossplane-provider-proxmox/config/provider.yaml" ]; then
        kubectl apply -f ../crossplane-provider-proxmox/config/provider.yaml
    else
        log "Warning: Crossplane provider manifest not found, skipping..."
    fi
}

wait_for_components() {
    log "Waiting for all components to be ready..."
    
    local components=(
        "argocd/argocd-server"
        "rancher-system/rancher"
        "crossplane-system/crossplane"
        "vault/vault"
        "monitoring/kube-prometheus-stack"
        "portal/portal"
    )
    
    for component in "${components[@]}"; do
        IFS='/' read -r namespace deployment <<< "${component}"
        if kubectl get deployment "${deployment}" -n "${namespace}" &> /dev/null; then
            log "Waiting for ${deployment} in ${namespace}..."
            kubectl wait --for=condition=available "deployment/${deployment}" -n "${namespace}" --timeout=600s || true
        fi
    done
}

print_access_info() {
    log "=== Access Information ==="
    
    # ArgoCD
    ARGOCD_PASSWORD=$(kubectl -n ${ARGOCD_NAMESPACE} get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" 2>/dev/null | base64 -d || echo "N/A")
    log "ArgoCD:"
    log "  URL: https://argocd.yourdomain.com"
    log "  Username: admin"
    log "  Password: ${ARGOCD_PASSWORD}"
    
    # Rancher
    log "Rancher:"
    log "  URL: https://rancher.yourdomain.com"
    
    # Portal
    log "Portal:"
    log "  URL: https://portal.yourdomain.com"
    
    # Grafana
    GRAFANA_PASSWORD=$(kubectl -n monitoring get secret kube-prometheus-stack-grafana -o jsonpath="{.data.admin-password}" 2>/dev/null | base64 -d || echo "admin")
    log "Grafana:"
    log "  URL: https://grafana.yourdomain.com"
    log "  Username: admin"
    log "  Password: ${GRAFANA_PASSWORD}"
}

main() {
    log "Starting control plane components installation..."
    
    check_prerequisites
    install_argocd
    install_argocd_applications
    install_crossplane_provider
    
    log "Waiting for components to be ready (this may take several minutes)..."
    wait_for_components
    
    print_access_info
    
    log "Installation completed!"
    log "Note: Some components may take additional time to fully sync from GitOps"
}

main "$@"

