# Installer le dashboard Kubernetes s'il n'existe pas
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.7.0/aio/deploy/recommended.yaml 2>$null

# Démarrer le proxy Kubernetes
Start-Process kubectl -ArgumentList "proxy" -WindowStyle Hidden

# Attendre que le proxy soit prêt
Start-Sleep -Seconds 5

# Créer le ServiceAccount (pas de --force, gestion propre)
if ($(kubectl get serviceaccount dashboard-admin -n kubernetes-dashboard -o name) -eq $null) {
    kubectl create serviceaccount dashboard-admin -n kubernetes-dashboard
    kubectl create clusterrolebinding dashboard-admin --clusterrole=cluster-admin --serviceaccount=kubernetes-dashboard:dashboard-admin
}

# Générer le jeton
$Token = kubectl create token dashboard-admin -n kubernetes-dashboard

# Informations du cluster
$ClusterName = kubectl config current-context
$Server = kubectl config view -o jsonpath="{.clusters[?(@.name==`"$ClusterName`")].cluster.server}"
$CACert = kubectl config view -o jsonpath="{.clusters[?(@.name==`"$ClusterName`")].cluster.certificate-authority-data}"

# Générer le kubeconfig
$Kubeconfig = @"
apiVersion: v1
kind: Config
clusters:
- name: $ClusterName
  cluster:
    server: $Server
    certificate-authority-data: $CACert
contexts:
- name: $ClusterName
  context:
    cluster: $ClusterName
    user: dashboard-admin
current-context: $ClusterName
users:
- name: dashboard-admin
  user:
    token: $Token
"@

# Sauvegarder
$Kubeconfig | Out-File -FilePath "C:\DevOpsProject\scripts\dashboard.kubeconfig" -Encoding UTF8

Write-Host "✅ kubeconfig généré : C:\DevOpsProject\scripts\dashboard.kubeconfig"

# Ouvrir le navigateur
$Url = "http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/"
Start-Process $Url

Write-Host "🌐 Dashboard ouvert dans le navigateur."
Write-Host "→ Choisissez 'Kubeconfig' et sélectionnez le fichier généré."   