# Fichier: python_cheats/cheatsheets/ArgoCD.txt
# Cheatsheet ArgoCD - Guide Ultra-Détaillé pour Grands Débutants


[OK] CONCEPTS FONDAMENTAUX (EXPLICATIONS TRÈS DÉTAILLÉES)

# === QU'EST-CE QUE ARGOCD ? ===

# Imagine que tu as une application (un site web, une API, etc.)
# Tu veux la déployer sur Kubernetes (une plateforme pour gérer des conteneurs)
# Mais déployer sur Kubernetes c'est compliqué:
# 1. Tu dois créer des fichiers YAML (configuration)
# 2. Tu dois les appliquer manuellement avec kubectl
# 3. Si tu changes le code, tu dois tout refaire
# 4. Comment savoir ce qui tourne actuellement?
# 5. Comment revenir en arrière si ça casse?
# = BEAUCOUP DE TRAVAIL MANUEL ET D'ERREURS POSSIBLES!

# ARGOCD = Outil qui automatise tout ça!
# Tu ne fais que:
# 1. Pousser ton code et ta config dans Git (GitHub, GitLab, etc.)
# 2. ArgoCD surveille Git automatiquement
# 3. Dès qu'il y a un changement, ArgoCD met à jour Kubernetes
# 4. BOOM! Ton app est déployée automatiquement
# 5. Interface web pour voir l'état de tout

# ArgoCD s'appelle un outil de "GitOps"
# GitOps = Git est la source de vérité
# = Tout ce qui est dans Git doit être dans Kubernetes
# = Si Git change, Kubernetes change automatiquement


# === POURQUOI UTILISER ARGOCD ? ===

# Problème SANS ArgoCD:
# Développeur 1: "J'ai déployé la version 1.2 hier"
# Développeur 2: "Moi j'ai déployé la 1.3 ce matin"
# Développeur 3: "Attends, quelle version tourne actuellement?"
# = CONFUSION TOTALE! Personne ne sait l'état réel

# Avec ArgoCD:
# - Git contient: version 1.3
# - ArgoCD affiche: "Version 1.3 déployée, tout synchronisé [OK]"
# - Tout le monde voit la même chose
# - Si quelqu'un déploie manuellement, ArgoCD détecte la différence
# - Peut automatiquement corriger (revenir à ce qui est dans Git)

# Avantages:
# [OK] Automatisation complète (plus de kubectl apply manuel)
# [OK] Traçabilité (historique Git = historique des déploiements)
# [OK] Rollback facile (revenir à un commit précédent)
# [OK] Interface graphique claire
# [OK] Notifications (Slack, email) quand un déploiement échoue
# [OK] Multi-cluster (gérer plusieurs clusters Kubernetes)
# [OK] Sécurité (contrôle d'accès, audit trail)


# === VOCABULAIRE ARGOCD (TRÈS IMPORTANT!) ===

# APPLICATION (ArgoCD Application)
# = Un projet que tu déploies avec ArgoCD
# = Contient: où est le code (Git), où déployer (Kubernetes cluster)
# Exemple: Si tu as une API backend, c'est UNE application ArgoCD
# Exemple: Si tu as un frontend, c'est UNE AUTRE application ArgoCD

# REPOSITORY (Dépôt Git)
# = L'endroit où ArgoCD lit ta configuration
# = Peut être: GitHub, GitLab, Bitbucket, ou un serveur Git privé
# = ArgoCD surveille ce repository pour les changements
# Exemple: https://github.com/ton-user/ton-projet

# SYNC STATUS (État de synchronisation)
# = Indique si ce qui tourne dans Kubernetes correspond à Git
# États possibles:
#   - Synced ([OK]): Kubernetes = Git (tout va bien!)
#   - OutOfSync ([ATTENTION]): Kubernetes ≠ Git (quelque chose a changé)
# Exemple: Tu as changé une ligne dans Git mais pas encore appliqué
#          -> Status = OutOfSync

# HEALTH STATUS (État de santé)
# = Indique si l'application fonctionne correctement
# États possibles:
#   - Healthy ([OK]): Tous les pods tournent, prêts à recevoir du trafic
#   - Progressing ([HOURGLASS_WITH_FLOWING_SAND]): En cours de démarrage
#   - Degraded ([ATTENTION]): Certains pods sont cassés
#   - Missing ([X]): Rien ne tourne
# Exemple: Si un pod crash en boucle -> Health = Degraded

# AUTO-SYNC (Synchronisation automatique)
# = Mode où ArgoCD déploie automatiquement dès qu'il voit un changement dans Git
# Si désactivé: Tu dois cliquer "Sync" manuellement
# Si activé: Dès que tu push dans Git, ArgoCD déploie automatiquement
# Recommandé: Désactivé pour la production (contrôle manuel)
#             Activé pour dev/staging (déploiement continu)

# SELF-HEAL (Auto-guérison)
# = Si quelqu'un modifie manuellement Kubernetes (sans passer par Git)
# = ArgoCD détecte la différence et revient automatiquement à l'état dans Git
# Exemple: Quelqu'un fait "kubectl edit" pour changer une config
#          -> ArgoCD détecte et annule le changement (revient à Git)

# PRUNE (Nettoyage)
# = Si tu supprimes un fichier dans Git, ArgoCD supprime aussi dans Kubernetes
# Sans prune: Le fichier reste dans Kubernetes même si supprimé de Git
# Avec prune: Le fichier est supprimé partout (cohérence totale)

# PROJECT (Projet ArgoCD)
# = Un groupe logique d'applications
# = Définit: quels repositories, quels clusters, quels namespaces
# = Utile pour organiser (équipe frontend, équipe backend, etc.)
# Par défaut: Il y a un projet "default"

# CLUSTER (Cluster Kubernetes)
# = Le serveur Kubernetes où ArgoCD déploie
# = Tu peux avoir plusieurs clusters (dev, staging, production)
# = ArgoCD peut déployer sur n'importe lequel

# MANIFEST (Fichier de configuration)
# = Les fichiers YAML qui décrivent ton app
# = Peut être: Kubernetes YAML pur, Helm charts, Kustomize, etc.
# Exemple: deployment.yaml, service.yaml, ingress.yaml


# === COMMENT ÇA MARCHE? (FLUX COMPLET) ===

# Étape 1: DÉVELOPPEMENT LOCAL
# Tu as un dossier avec:
# myapp/
# ├── app.py (ton code Python)
# ├── Dockerfile (pour créer l'image Docker)
# └── k8s/
#     ├── deployment.yaml (config Kubernetes)
#     └── service.yaml

# Étape 2: CRÉER L'IMAGE DOCKER
# Tu build l'image Docker:
docker build -t myapp:1.0 .
docker push myregistry.com/myapp:1.0

# Étape 3: POUSSER LA CONFIG DANS GIT
# Tu modifies deployment.yaml pour utiliser l'image:
# image: myregistry.com/myapp:1.0
git add k8s/
git commit -m "Deploy version 1.0"
git push origin main

# Étape 4: ARGOCD DÉTECTE LE CHANGEMENT
# ArgoCD surveille ton repository Git toutes les 3 minutes (par défaut)
# Il voit: "Oh! Il y a un nouveau commit!"
# Il compare: Ce qui est dans Git vs ce qui est dans Kubernetes
# Résultat: "OutOfSync" (différence détectée)

# Étape 5: SYNCHRONISATION
# Soit manuellement (tu cliques "Sync" dans l'interface)
# Soit automatiquement (si auto-sync est activé)
# ArgoCD lit les fichiers YAML dans Git
# ArgoCD applique ces fichiers dans Kubernetes (kubectl apply)
# Résultat: Sync Status = "Synced"

# Étape 6: VÉRIFICATION DE SANTÉ
# ArgoCD surveille les pods Kubernetes
# Il attend que tous les pods soient "Ready"
# Si les pods démarrent correctement: Health = "Healthy"
# Si un pod crash: Health = "Degraded"

# Étape 7: ÉTAT FINAL
# Interface ArgoCD affiche:
# [OK] Sync Status: Synced (Git = Kubernetes)
# [OK] Health Status: Healthy (Tout fonctionne)
# [OK] Dernière sync: il y a 2 minutes
# [OK] Commit: abc1234 "Deploy version 1.0"

# Étape 8: MISE À JOUR
# Tu veux déployer la version 1.1:
# 1. Build nouvelle image: docker build -t myapp:1.1 .
# 2. Push: docker push myregistry.com/myapp:1.1
# 3. Modifie deployment.yaml: image: myregistry.com/myapp:1.1
# 4. Commit: git commit -am "Update to 1.1"
# 5. Push: git push
# 6. ArgoCD détecte automatiquement
# 7. Sync (manuel ou auto)
# 8. Nouvelle version déployée!

# Étape 9: ROLLBACK SI PROBLÈME
# Version 1.1 a un bug! Tu veux revenir à 1.0
# Solution simple:
git revert HEAD  # Annule le dernier commit
git push
# ArgoCD détecte, sync, et revient à 1.0 automatiquement!


# === ARCHITECTURE ARGOCD ===

# ArgoCD est composé de plusieurs services:

# 1. API Server (argocd-server)
#    = Interface REST API + UI Web
#    = C'est ce que tu visites dans ton navigateur
#    = Port: 8080 (HTTP) ou 443 (HTTPS)

# 2. Repository Server (argocd-repo-server)
#    = Service qui lit Git
#    = Clone les repositories, lit les fichiers YAML
#    = Cache les manifests pour performance

# 3. Application Controller (argocd-application-controller)
#    = Cerveau d'ArgoCD
#    = Surveille Kubernetes et Git
#    = Détecte les différences (OutOfSync)
#    = Exécute les syncs

# 4. Redis
#    = Cache pour stocker l'état temporaire
#    = Améliore les performances

# 5. Dex (Optionnel)
#    = Service d'authentification SSO
#    = Permet de se connecter avec Google, GitHub, LDAP, etc.

# Schéma simplifié:
#
# [Développeur] -> push -> [Git Repository]
#                              v
#                         [ArgoCD]
#                         Repository Server lit Git
#                         Application Controller compare
#                              v
#                    [Kubernetes Cluster]
#                    Déploie/Met à jour les apps
#                              v
#                      [Interface Web]
#                      Affiche l'état


[OK] INSTALLATION SUPER DÉTAILLÉE

# === PRÉREQUIS ===

# Avant d'installer ArgoCD, tu DOIS avoir:

# 1. UN CLUSTER KUBERNETES FONCTIONNEL
# Options:
#   - Minikube (local, pour apprendre)
#   - Kind (Kubernetes in Docker, local)
#   - K3s (léger, pour petits serveurs)
#   - GKE (Google Kubernetes Engine, cloud)
#   - EKS (Amazon Elastic Kubernetes Service, cloud)
#   - AKS (Azure Kubernetes Service, cloud)

# Comment vérifier?
kubectl version --short
# Doit afficher:
# Client Version: v1.28.x
# Server Version: v1.28.x

kubectl get nodes
# Doit afficher au moins 1 nœud en état "Ready"

# Si tu n'as pas de cluster: Installe Minikube
# macOS:
brew install minikube
minikube start

# Linux:
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube
minikube start

# Windows:
# Télécharge: https://github.com/kubernetes/minikube/releases/latest/download/minikube-installer.exe
# Installe et lance: minikube start


# 2. KUBECTL INSTALLÉ
# kubectl = Outil en ligne de commande pour Kubernetes

# Vérifier:
kubectl version --client
# Doit afficher: Client Version: v1.28.x

# Si pas installé:
# macOS:
brew install kubectl

# Linux:
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl

# Windows:
# Télécharge: https://dl.k8s.io/release/v1.28.0/bin/windows/amd64/kubectl.exe
# Ajoute au PATH


# 3. ACCÈS ADMINISTRATEUR AU CLUSTER
# Tu dois pouvoir créer des namespaces, des services, etc.

# Vérifier:
kubectl auth can-i create namespace
# Doit afficher: yes

# Si "no": Tu n'as pas les droits suffisants!


# === MÉTHODE 1: INSTALLATION VIA KUBECTL (RECOMMANDÉE) ===

# C'est la méthode la plus simple et directe

# Étape 1: Créer le namespace ArgoCD
# namespace = un espace isolé dans Kubernetes
# On va mettre tous les composants ArgoCD dedans

kubectl create namespace argocd

# Affiche:
# namespace/argocd created

# Vérifier:
kubectl get namespace argocd
# Affiche:
# NAME     STATUS   AGE
# argocd   Active   5s


# Étape 2: Installer ArgoCD
# On applique le manifeste officiel d'ArgoCD
# Ce manifeste contient TOUS les composants (API server, controller, etc.)

kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

# Explications:
# -n argocd = Dans le namespace "argocd"
# -f URL = Applique le fichier depuis cette URL

# Affiche plein de lignes:
# customresourcedefinition.apiextensions.k8s.io/applications.argoproj.io created
# customresourcedefinition.apiextensions.k8s.io/applicationsets.argoproj.io created
# serviceaccount/argocd-application-controller created
# ...
# service/argocd-server created
# deployment.apps/argocd-server created
# ...

# IMPORTANT: Ça prend 2-3 minutes pour que tout démarre!


# Étape 3: Vérifier l'installation
# On vérifie que tous les pods sont "Running"

kubectl get pods -n argocd

# Affiche quelque chose comme:
# NAME                                  READY   STATUS    RESTARTS   AGE
# argocd-application-controller-0       1/1     Running   0          2m
# argocd-applicationset-controller-...  1/1     Running   0          2m
# argocd-dex-server-...                 1/1     Running   0          2m
# argocd-notifications-controller-...   1/1     Running   0          2m
# argocd-redis-...                      1/1     Running   0          2m
# argocd-repo-server-...                1/1     Running   0          2m
# argocd-server-...                     1/1     Running   0          2m

# Si STATUS = "Running" et READY = "1/1" partout -> TOUT VA BIEN!
# Si STATUS = "Pending" ou "CrashLoopBackOff" -> Attends 1-2 minutes
# Si ça ne change pas après 5 minutes -> Problème! (voir section Dépannage)


# Étape 4: Exposer l'interface web
# Par défaut, ArgoCD n'est pas accessible depuis l'extérieur
# On doit "exposer" le service argocd-server

# Option A: Port-forward (SIMPLE, pour test local)
# = Crée un tunnel temporaire de ton ordinateur vers Kubernetes

kubectl port-forward svc/argocd-server -n argocd 8080:443

# Explications:
# svc/argocd-server = Le service ArgoCD
# -n argocd = Dans le namespace argocd
# 8080:443 = Port local 8080 -> Port service 443

# Affiche:
# Forwarding from 127.0.0.1:8080 -> 8080
# Forwarding from [::1]:8080 -> 8080

# IMPORTANT: Laisse ce terminal ouvert!
# Si tu le fermes, le tunnel se ferme aussi

# Maintenant ouvre un navigateur: https://localhost:8080
# Tu vois l'interface ArgoCD! (Accepte l'avertissement SSL)

# Option B: LoadBalancer (pour production, sur cloud)
# Change le type de service en LoadBalancer

kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "LoadBalancer"}}'

# Attends 1-2 minutes que le LoadBalancer soit créé
# Récupère l'IP externe:

kubectl get svc argocd-server -n argocd

# Affiche:
# NAME            TYPE           CLUSTER-IP      EXTERNAL-IP      PORT(S)
# argocd-server   LoadBalancer   10.96.123.45    35.123.45.67     80:30123/TCP,443:31234/TCP

# EXTERNAL-IP = L'IP publique!
# Ouvre un navigateur: https://35.123.45.67
# Interface ArgoCD accessible!

# Option C: Ingress (pour production avec nom de domaine)
# Tu veux accéder via argocd.mondomaine.com
# Nécessite un Ingress Controller (nginx, traefik, etc.)

# Exemple avec nginx-ingress:
cat <<EOF | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: argocd-server-ingress
  namespace: argocd
  annotations:
    nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
    nginx.ingress.kubernetes.io/ssl-passthrough: "true"
spec:
  ingressClassName: nginx
  rules:
  - host: argocd.mondomaine.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: argocd-server
            port:
              number: 443
EOF

# Configure ton DNS:
# argocd.mondomaine.com -> IP de ton LoadBalancer/Ingress

# Accède via: https://argocd.mondomaine.com


# Étape 5: Récupérer le mot de passe initial
# ArgoCD génère automatiquement un mot de passe admin

# Le mot de passe est stocké dans un Secret Kubernetes

kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo

# Affiche quelque chose comme:
# Kj8nB2mP9qRsT4vW

# IMPORTANT: Note ce mot de passe quelque part!

# Explications:
# get secret = Récupère le secret
# -o jsonpath="{.data.password}" = Extrait le champ "password"
# base64 -d = Décode le base64
# ; echo = Ajoute une nouvelle ligne

# Si erreur "base64: invalid input" sur macOS:
# Utilise cette commande alternative:
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 --decode


# Étape 6: Se connecter à l'interface web
# Ouvre le navigateur: https://localhost:8080 (ou ton IP/domaine)

# Tu vois un formulaire de connexion:
# Username: admin
# Password: [Le mot de passe récupéré à l'étape 5]

# Clique "SIGN IN"
# TU ES CONNECTÉ!

# Tu vois le dashboard ArgoCD:
# - Aucune application pour le moment (normal, c'est une installation fraîche)
# - Menu à gauche: Applications, Settings, User Info
# - Barre supérieure: "NEW APP" pour créer une application


# Étape 7: Changer le mot de passe admin (RECOMMANDÉ!)
# Le mot de passe initial est aléatoire et difficile
# Change-le pour quelque chose que tu te rappelles

# Option A: Via l'interface web
# 1. Clique sur "User Info" (en haut à droite)
# 2. Clique "Update Password"
# 3. Entre: Current Password (celui de l'étape 5)
# 4. Entre: New Password (ton nouveau mot de passe)
# 5. Confirme: Confirm New Password
# 6. Clique "Save"

# Option B: Via CLI (voir section CLI plus bas)


# === MÉTHODE 2: INSTALLATION VIA HELM ===

# Helm = Gestionnaire de packages pour Kubernetes
# Si tu préfères utiliser Helm:

# Étape 1: Installer Helm (si pas déjà fait)
# macOS:
brew install helm

# Linux:
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash

# Windows:
# Télécharge: https://github.com/helm/helm/releases


# Étape 2: Ajouter le repository Helm d'ArgoCD
helm repo add argo https://argoproj.github.io/argo-helm

# Mettre à jour:
helm repo update


# Étape 3: Installer ArgoCD via Helm
helm install argocd argo/argo-cd --namespace argocd --create-namespace

# Affiche:
# NAME: argocd
# LAST DEPLOYED: ...
# NAMESPACE: argocd
# STATUS: deployed


# Étape 4: Suivre les étapes 3-7 de la méthode 1
# (Vérifier pods, exposer service, récupérer mot de passe)


# === MÉTHODE 3: INSTALLATION DANS UN ENVIRONNEMENT HA (HAUTE DISPONIBILITÉ) ===

# Pour production, tu veux plusieurs réplicas (redondance)

kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/ha/install.yaml

# Cette version crée:
# - 3 réplicas du repo-server
# - 3 réplicas du API server
# - Redis en mode HA
# = Si un pod crash, les autres continuent


[OK] ARGOCD CLI - INSTALLATION ET UTILISATION

# === QU'EST-CE QUE LA CLI ARGOCD? ===

# CLI = Command Line Interface = Outil en ligne de commande
# Permet de contrôler ArgoCD depuis le terminal
# Alternatives à l'interface web
# Utile pour: automation, scripts, CI/CD

# === INSTALLATION DE LA CLI ===

# === macOS ===
brew install argocd

# Vérifier:
argocd version
# Affiche: argocd: v2.9.x

# === Linux ===
# Télécharger le binaire:
curl -sSL -o argocd-linux-amd64 https://github.com/argoproj/argo-cd/releases/latest/download/argocd-linux-amd64

# Installer:
sudo install -m 555 argocd-linux-amd64 /usr/local/bin/argocd

# Supprimer le fichier téléchargé:
rm argocd-linux-amd64

# Vérifier:
argocd version

# === Windows ===
# Télécharger: https://github.com/argoproj/argo-cd/releases/latest/download/argocd-windows-amd64.exe
# Renommer en: argocd.exe
# Ajouter le dossier au PATH

# Vérifier (PowerShell):
argocd version


# === SE CONNECTER À ARGOCD VIA CLI ===

# Méthode 1: Via port-forward (local)
# D'abord, crée un port-forward (dans un autre terminal):
kubectl port-forward svc/argocd-server -n argocd 8080:443

# Dans ton terminal principal:
argocd login localhost:8080

# Affiche:
# WARNING: server certificate had error: x509: certificate signed by unknown authority. Proceed insecurely (y/n)?
# Tape: y

# Demande:
# Username: admin
# Password: [Ton mot de passe]

# Affiche:
# 'admin:login' logged in successfully

# Méthode 2: Via IP externe ou domaine
argocd login argocd.mondomaine.com

# Ou avec IP:
argocd login 35.123.45.67

# Suit les mêmes étapes

# Méthode 3: Avec des options
argocd login localhost:8080 --username admin --password 'VotreMdp' --insecure

# --insecure = Accepte les certificats auto-signés
# Utile pour éviter l'avertissement


# === VÉRIFIER LA CONNEXION ===

argocd account get-user-info

# Affiche:
# Logged In: true
# Username: admin
# Issuer: argocd
# Groups: [...]


# === CHANGER LE MOT DE PASSE VIA CLI ===

argocd account update-password

# Demande:
# *** Enter current password:
# *** Enter new password:
# *** Confirm new password:

# Affiche:
# Password updated


# === COMMANDES CLI ESSENTIELLES ===

# Voir toutes les applications:
argocd app list

# Affiche:
# NAME        CLUSTER                         NAMESPACE  PROJECT  STATUS  HEALTH   SYNCPOLICY  CONDITIONS
# (vide si aucune app)

# Créer une application:
argocd app create myapp \
  --repo https://github.com/user/repo.git \
  --path k8s/ \
  --dest-server https://kubernetes.default.svc \
  --dest-namespace default

# Synchroniser une application:
argocd app sync myapp

# Voir les détails d'une application:
argocd app get myapp

# Supprimer une application:
argocd app delete myapp

# Voir les logs en temps réel:
argocd app logs myapp --follow


[OK] CRÉER VOTRE PREMIÈRE APPLICATION (GUIDE PAS-À-PAS)

# === CONTEXTE ===

# Tu vas créer une application simple:
# - Un serveur web nginx
# - Qui affiche une page HTML
# - Déployée via ArgoCD

# === ÉTAPE 1: CRÉER LE REPOSITORY GIT ===

# Sur GitHub, GitLab ou autre:
# 1. Crée un nouveau repository: "argocd-demo"
# 2. Clone-le localement:

git clone https://github.com/ton-user/argocd-demo.git
cd argocd-demo


# === ÉTAPE 2: CRÉER LES MANIFESTS KUBERNETES ===

# Crée un dossier pour les fichiers Kubernetes:
mkdir k8s
cd k8s

# === Fichier 1: deployment.yaml ===
# Crée le fichier k8s/deployment.yaml:

cat > deployment.yaml << 'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-demo
  labels:
    app: nginx-demo
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx-demo
  template:
    metadata:
      labels:
        app: nginx-demo
    spec:
      containers:
      - name: nginx
        image: nginx:1.25
        ports:
        - containerPort: 80
        resources:
          requests:
            memory: "64Mi"
            cpu: "100m"
          limits:
            memory: "128Mi"
            cpu: "200m"
EOF

# Explications:
# apiVersion: apps/v1 = Version de l'API Kubernetes
# kind: Deployment = Type de ressource (Deployment)
# metadata.name = Nom du déploiement
# spec.replicas: 2 = 2 instances (pods) de nginx
# spec.template.spec.containers = Définition du conteneur
#   - image: nginx:1.25 = Image Docker à utiliser
#   - containerPort: 80 = Port exposé
#   - resources = Limites CPU/mémoire


# === Fichier 2: service.yaml ===
# Crée le fichier k8s/service.yaml:

cat > service.yaml << 'EOF'
apiVersion: v1
kind: Service
metadata:
  name: nginx-demo-service
spec:
  selector:
    app: nginx-demo
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  type: ClusterIP
EOF

# Explications:
# kind: Service = Expose les pods via un service
# spec.selector = Sélectionne les pods avec label "app: nginx-demo"
# spec.ports = Port 80 (externe) -> Port 80 (pods)
# type: ClusterIP = Accessible uniquement à l'intérieur du cluster


# === ÉTAPE 3: POUSSER DANS GIT ===

# Revenir à la racine du projet:
cd ..

# Vérifier la structure:
tree
# ou
find .

# Affiche:
# .
# └── k8s
#     ├── deployment.yaml
#     └── service.yaml

# Ajouter à Git:
git add k8s/
git commit -m "Add Kubernetes manifests for nginx demo"
git push origin main

# Vérifier sur GitHub/GitLab que les fichiers sont bien là


# === ÉTAPE 4: CRÉER L'APPLICATION (VIA INTERFACE WEB) - DÉTAILS DU FORMULAIRE ===

# Tu es sur la page "+ NEW APP"
# Voici TOUS les champs à remplir:

# SECTION: GENERAL
# ----------------

# Application Name: nginx-demo
# Explications: 
# - Nom unique de ton application
# - Utilise des lettres minuscules, chiffres, tirets (-)
# - Pas d'espaces, pas de caractères spéciaux
# - Ce nom sera utilisé partout dans ArgoCD
# Exemple valide: nginx-demo, my-app-v2, frontend-prod
# Exemple invalide: Nginx Demo, my_app, app@prod

# Project: default
# Explications:
# - Projet ArgoCD auquel appartient l'application
# - "default" existe par défaut
# - Tu peux créer d'autres projets plus tard (voir section Projets)
# - Un projet définit: qui peut déployer où, avec quelles sources

# SYNC POLICY: Manual
# Explications:
# - Manual = Tu dois cliquer "Sync" pour déployer
# - Automatic = Déploiement automatique dès qu'il y a un changement dans Git
# - Recommandation: Manual pour commencer (tu contrôles tout)
# Laisse MANUAL pour l'instant


# SECTION: SOURCE (D'OÙ VIENT TON CODE)
# --------------------------------------

# Repository URL: https://github.com/ton-user/argocd-demo.git
# Explications:
# - L'URL de ton repository Git
# - Peut être: HTTPS ou SSH
# - Formats acceptés:
#   HTTPS: https://github.com/user/repo.git
#   SSH: git@github.com:user/repo.git
#   Privé: Nécessite des credentials (voir section Repositories)

# Revision: HEAD
# Explications:
# - Quelle version du code utiliser
# - HEAD = La dernière version de la branche par défaut (main/master)
# - Peut être: 
#   - Une branche: main, develop, feature/new-ui
#   - Un tag: v1.0.0, release-2023-12
#   - Un commit SHA: abc123def456
# Pour commencer, laisse HEAD

# Path: k8s/
# Explications:
# - Le dossier dans ton repository qui contient les manifests
# - Si manifests à la racine: laisse vide ou met "."
# - Si dans un sous-dossier: indique le chemin
# - Dans notre cas: k8s/ (le dossier qu'on a créé)
# - Peut avoir plusieurs niveaux: apps/backend/k8s/


# SECTION: DESTINATION (OÙ DÉPLOYER)
# -----------------------------------

# Cluster URL: https://kubernetes.default.svc
# Explications:
# - Le cluster Kubernetes où déployer
# - Par défaut: Le cluster où ArgoCD est installé
# - https://kubernetes.default.svc = "ce cluster-ci"
# - Pour déployer sur un autre cluster: ajoute-le d'abord (voir section Multi-Cluster)
# Laisse la valeur par défaut pour l'instant

# Namespace: default
# Explications:
# - Le namespace Kubernetes où créer les ressources
# - "default" = le namespace par défaut de Kubernetes
# - Peut être: dev, staging, prod, mon-app, etc.
# - IMPORTANT: Le namespace doit déjà exister OU active "AUTO-CREATE NAMESPACE"
# Pour l'instant: default (existe toujours)


# SECTION: HELM (IGNORE SI TU N'UTILISES PAS HELM)
# ------------------------------------------------
# Laisse vide pour l'instant (on utilise des manifests YAML purs)


# SECTION: KUSTOMIZE (IGNORE SI TU N'UTILISES PAS KUSTOMIZE)
# ----------------------------------------------------------
# Laisse vide pour l'instant


# SECTION: DIRECTORY (OPTIONS POUR MANIFESTS YAML)
# ------------------------------------------------

# Recurse: [ ] (décoché)
# Explications:
# - Si coché: ArgoCD lit aussi les sous-dossiers
# - Si décoché: ArgoCD lit uniquement k8s/
# Exemple de structure:
# k8s/
# ├── deployment.yaml
# ├── service.yaml
# └── monitoring/
#     └── servicemonitor.yaml
# Recurse décoché: Lit deployment.yaml et service.yaml
# Recurse coché: Lit TOUT (deployment, service, servicemonitor)
# Laisse DÉCOCHÉ pour l'instant

# Include/Exclude: (vide)
# Explications:
# - Permet de filtrer les fichiers
# - Exemple Include: *.yaml (uniquement fichiers YAML)
# - Exemple Exclude: test-*.yaml (ignore les fichiers de test)
# Laisse VIDE pour l'instant


# SECTION: SYNC OPTIONS (OPTIONS AVANCÉES)
# ----------------------------------------

# Clique sur "SYNC OPTIONS" pour voir les options

# AUTO-CREATE NAMESPACE: [ ] (décoché)
# Explications:
# - Si coché: ArgoCD crée le namespace s'il n'existe pas
# - Si décoché: Erreur si le namespace n'existe pas
# - Utile si tu déploies dans un nouveau namespace
# Laisse DÉCOCHÉ (on utilise "default" qui existe)

# PRUNE RESOURCES: [ ] (décoché)
# Explications:
# - Si coché: Supprime les ressources qui ne sont plus dans Git
# - Exemple: Tu supprimes service.yaml de Git
#   -> ArgoCD supprime aussi le service de Kubernetes
# - ATTENTION: Peut supprimer des choses importantes!
# Recommandation: Active seulement quand tu es sûr
# Laisse DÉCOCHÉ pour l'instant

# SELF HEAL: [ ] (décoché)
# Explications:
# - Si coché: ArgoCD corrige automatiquement les modifications manuelles
# - Exemple: Quelqu'un fait "kubectl edit deployment nginx-demo"
#   -> ArgoCD détecte et annule la modification (revient à Git)
# - Utile en production pour éviter les changements sauvages
# Laisse DÉCOCHÉ pour apprendre (tu veux voir les différences)


# VALIDATION: Le formulaire vérifie automatiquement
# Si tout est correct: Le bouton "CREATE" devient bleu
# Si erreur: Message rouge sous le champ problématique


# ÉTAPE 5: CRÉER L'APPLICATION

# Clique sur le bouton "CREATE" (en haut du formulaire)

# ArgoCD fait:
# 1. Valide tous les champs
# 2. Connecte au repository Git
# 3. Lit les fichiers dans k8s/
# 4. Analyse les manifests
# 5. Crée l'application

# Tu es redirigé vers la vue de l'application
# Tu vois une carte avec:
# - Nom: nginx-demo
# - Status: OutOfSync (normal! pas encore synchronisé)
# - Health: Missing (normal! rien n'est déployé encore)


# === ÉTAPE 6: SYNCHRONISER L'APPLICATION ===

# Tu vois maintenant la vue détaillée de l'application

# En haut à droite, clique sur le bouton "SYNC"

# Une fenêtre popup apparaît: "Synchronize application nginx-demo"

# OPTIONS DE SYNC:
# ---------------

# REVISION: HEAD (main)
# Explications:
# - Quelle version synchroniser
# - Par défaut: La version configurée (HEAD)
# - Tu peux changer pour un commit spécifique, une branche, un tag
# Laisse HEAD

# DRY RUN: [ ] (décoché)
# Explications:
# - Si coché: Simulation (ne déploie pas vraiment)
# - ArgoCD montre CE QUI SERAIT fait sans le faire
# - Utile pour tester avant un vrai déploiement
# Laisse DÉCOCHÉ (on veut vraiment déployer)

# PRUNE: [ ] (décoché)
# Explications:
# - Même chose que l'option globale
# - Active uniquement pour cette sync
# Laisse DÉCOCHÉ

# APPLY ONLY: [ ] (décoché)
# Explications:
# - Si coché: Applique sans vérifier la santé après
# - Si décoché: Applique ET attend que tout soit "Healthy"
# Laisse DÉCOCHÉ (on veut voir si ça marche)

# FORCE: [ ] (décoché)
# Explications:
# - Si coché: Force le remplacement même si conflit
# - Dangereux! Peut écraser des données
# - Utilise seulement si tu sais ce que tu fais
# Laisse DÉCOCHÉ


# RESOURCES À SYNCHRONISER:
# -------------------------

# Tu vois la liste des ressources détectées:
# [x] Deployment nginx-demo
# [x] Service nginx-demo-service

# Toutes sont cochées par défaut (c'est ce qu'on veut)

# Tu peux décocher si tu veux synchroniser seulement certaines ressources
# Exemple: Décocher Service si tu veux déployer seulement le Deployment
# Laisse TOUT COCHÉ


# SYNCHRONIZE!
# ------------

# Clique sur le bouton "SYNCHRONIZE" (en bas de la popup)

# ArgoCD commence la synchronisation:
# 1. Clone le repository Git
# 2. Lit deployment.yaml et service.yaml
# 3. Exécute: kubectl apply -f deployment.yaml
# 4. Exécute: kubectl apply -f service.yaml
# 5. Surveille l'état des ressources

# La popup se ferme
# Tu reviens à la vue de l'application


# === ÉTAPE 7: OBSERVER LE DÉPLOIEMENT ===

# INTERFACE GRAPHIQUE:
# -------------------

# Tu vois maintenant un graphique de dépendances:

#     [Application: nginx-demo]
#              |
#      --------|--------
#      |               |
# [Deployment]    [Service]
#      |
#   ---|---
#   |     |
# [Pod] [Pod]

# CODES COULEUR:
# - Bleu: Progressing (en cours de démarrage)
# - Vert: Healthy (tout va bien!)
# - Jaune: Degraded (problème)
# - Rouge: Failed (échec)
# - Gris: Missing (n'existe pas)

# ÉVOLUTION:
# 1. Deployment: Bleu (Progressing) - Création en cours
# 2. Pods: Bleu (Progressing) - Démarrage de nginx
# 3. Pods: Vert (Healthy) - nginx prêt à recevoir du trafic
# 4. Service: Vert (Healthy) - Service opérationnel
# 5. Deployment: Vert (Healthy) - Tout est prêt!

# TEMPS: Ça prend 10-30 secondes selon la vitesse de téléchargement de l'image


# STATUT EN HAUT:
# --------------

# Tu vois deux badges principaux:

# 1. SYNC STATUS: Synced (vert)
# Explications:
# - Kubernetes = Git (parfaite synchronisation)
# - Ce qui tourne correspond exactement à ce qui est dans Git

# 2. HEALTH STATUS: Healthy (vert)
# Explications:
# - Toutes les ressources fonctionnent correctement
# - Pods en "Running" et "Ready"
# - Service opérationnel


# INFORMATIONS SUPPLÉMENTAIRES:
# -----------------------------

# LAST SYNC: Just now (il y a quelques secondes)
# SYNC RESULT: Sync OK
# REVISION: abc123 (le commit SHA)
# COMMIT MESSAGE: "Add Kubernetes manifests for nginx demo"


# === ÉTAPE 8: EXPLORER L'APPLICATION ===

# CLIQUER SUR UN ÉLÉMENT:
# ----------------------

# Clique sur le rectangle "Deployment: nginx-demo"

# Une panneau latéral s'ouvre à droite avec:

# SUMMARY (Résumé):
# - Name: nginx-demo
# - Namespace: default
# - Kind: Deployment
# - API Version: apps/v1
# - Created: 2 minutes ago

# MANIFEST (Configuration actuelle):
# - Affiche le YAML complet du Deployment dans Kubernetes
# - C'est ce qui TOURNE RÉELLEMENT (pas ce qui est dans Git)
# - Tu peux le comparer avec ton fichier Git

# DESIRED MANIFEST (Configuration désirée):
# - Affiche le YAML depuis Git
# - C'est ce qui DEVRAIT tourner
# - Normalement identique à MANIFEST (puisque Synced)

# EVENTS (Événements):
# - Liste des événements Kubernetes
# - Exemple:
#   * Scaled up replica set to 2
#   * Created pod nginx-demo-abc123
#   * Created pod nginx-demo-def456
#   * Deployment successfully rolled out

# LOGS (Journaux):
# - Pas applicable pour un Deployment (pas de logs directs)
# - Disponible pour les Pods


# CLIQUER SUR UN POD:
# ------------------

# Clique sur un des rectangles "Pod: nginx-demo-xxxxx"

# Panneau latéral avec:

# SUMMARY:
# - Name: nginx-demo-7b8c9d-abc12
# - Node: minikube (le serveur où il tourne)
# - Status: Running (en cours d'exécution)
# - Restarts: 0 (nombre de redémarrages)
# - Age: 3 minutes

# MANIFEST: (YAML du Pod)

# LOGS: (LES LOGS NGINX!)
# Tu vois les logs en temps réel du conteneur nginx:
# /docker-entrypoint.sh: Configuration complete; ready for start up
# 127.0.0.1 - - [date] "GET / HTTP/1.1" 200 ...

# Bouton "FOLLOW" pour activer le mode suivi en temps réel
# Bouton "DOWNLOAD" pour télécharger les logs


# === ÉTAPE 9: TESTER L'APPLICATION ===

# ACCÉDER À NGINX:
# ---------------

# Nginx tourne dans Kubernetes mais n'est pas accessible depuis l'extérieur
# (Service type: ClusterIP = interne uniquement)

# Solution: Port-forward

# Ouvre un terminal:
kubectl port-forward -n default svc/nginx-demo-service 8081:80

# Affiche:
# Forwarding from 127.0.0.1:8081 -> 80

# Ouvre un navigateur: http://localhost:8081

# TU VOIS LA PAGE NGINX PAR DÉFAUT!
# "Welcome to nginx!"

# FÉLICITATIONS! Ton application tourne via ArgoCD! [BRAVO]


# === ÉTAPE 10: FAIRE UNE MODIFICATION ===

# MODIFIER LE NOMBRE DE REPLICAS:
# -------------------------------

# Retourne dans ton repository Git local
cd ~/argocd-demo

# Édite k8s/deployment.yaml
# Change: replicas: 2
# En: replicas: 3

# Ou en ligne de commande:
sed -i 's/replicas: 2/replicas: 3/' k8s/deployment.yaml

# Commit et push:
git add k8s/deployment.yaml
git commit -m "Scale to 3 replicas"
git push origin main


# OBSERVER DANS ARGOCD:
# ---------------------

# Retourne dans l'interface ArgoCD
# REFRESH (bouton en haut) ou attends 3 minutes (refresh auto)

# Le status change:
# SYNC STATUS: OutOfSync (orange)

# Explications:
# - ArgoCD détecte une différence entre Git et Kubernetes
# - Git dit: 3 replicas
# - Kubernetes a: 2 replicas
# - Donc: OutOfSync!

# Clique sur "APP DIFF" (en haut) pour voir la différence

# Tu vois:
# - Ligne rouge: replicas: 2 (ce qui est dans Kubernetes)
# - Ligne verte: replicas: 3 (ce qui est dans Git)

# C'est comme un "git diff" mais entre Git et Kubernetes!


# SYNCHRONISER LA MODIFICATION:
# -----------------------------

# Clique sur "SYNC" -> "SYNCHRONIZE"

# ArgoCD applique le changement:
# 1. Lit deployment.yaml avec replicas: 3
# 2. Exécute: kubectl apply -f deployment.yaml
# 3. Kubernetes crée un 3ème pod

# Dans l'interface graphique:
# - Un nouveau rectangle "Pod" apparaît
# - D'abord Bleu (Progressing)
# - Puis Vert (Healthy)

# MAINTENANT TU AS 3 PODS NGINX! [OK]


[OK] MÉTHODES ALTERNATIVES DE CRÉATION D'APPLICATION

# === MÉTHODE 2: VIA LA CLI ARGOCD ===

# Même résultat que l'interface web, mais en ligne de commande

argocd app create nginx-demo \
  --repo https://github.com/ton-user/argocd-demo.git \
  --path k8s/ \
  --dest-server https://kubernetes.default.svc \
  --dest-namespace default

# Explications des options:
# --repo = URL du repository Git
# --path = Chemin dans le repository
# --dest-server = Cluster Kubernetes de destination
# --dest-namespace = Namespace de destination

# Affiche:
# application 'nginx-demo' created

# Synchroniser:
argocd app sync nginx-demo

# Affiche:
# TIMESTAMP                  GROUP        KIND   NAMESPACE                  NAME    STATUS    HEALTH        HOOK  MESSAGE
# 2024-01-15T10:30:00+00:00            Service     default  nginx-demo-service    Synced   Healthy
# 2024-01-15T10:30:00+00:00   apps  Deployment     default          nginx-demo    Synced   Healthy

# Voir l'état:
argocd app get nginx-demo

# Affiche un résumé complet:
# Name:               nginx-demo
# Project:            default
# Server:             https://kubernetes.default.svc
# Namespace:          default
# URL:                https://localhost:8080/applications/nginx-demo
# Repo:               https://github.com/ton-user/argocd-demo.git
# Target:             HEAD
# Path:               k8s/
# SyncWindow:         Sync Allowed
# Sync Policy:        <none>
# Sync Status:        Synced to HEAD (abc123)
# Health Status:      Healthy
# 
# GROUP  KIND        NAMESPACE  NAME                STATUS  HEALTH   HOOK  MESSAGE
#        Service     default    nginx-demo-service  Synced  Healthy        service/nginx-demo-service created
# apps   Deployment  default    nginx-demo          Synced  Healthy        deployment.apps/nginx-demo created


# === MÉTHODE 3: VIA MANIFEST YAML KUBERNETES ===

# Tu peux définir l'Application ArgoCD elle-même dans un fichier YAML!
# C'est du "GitOps sur GitOps" [SHOCKED_FACE_WITH_EXPLODING_HEAD]

# Crée application.yaml dans ton repository:

cat > application.yaml << 'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: nginx-demo
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/ton-user/argocd-demo.git
    targetRevision: HEAD
    path: k8s/
  destination:
    server: https://kubernetes.default.svc
    namespace: default
  syncPolicy:
    automated:
      prune: false
      selfHeal: false
    syncOptions:
    - CreateNamespace=false
EOF

# Applique ce fichier:
kubectl apply -f application.yaml

# ArgoCD crée automatiquement l'application!

# Avantage:
# - L'application elle-même est versionnée dans Git
# - Tu peux gérer des dizaines d'applications facilement
# - Tout est reproductible


# === MÉTHODE 4: VIA APPLICATIONSET (POUR CRÉER PLUSIEURS APPS) ===

# ApplicationSet = Créer plusieurs applications d'un coup
# Utile pour: déployer la même app dans plusieurs environnements

# Exemple: Créer nginx-demo-dev, nginx-demo-staging, nginx-demo-prod

cat > applicationset.yaml << 'EOF'
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: nginx-demo-envs
  namespace: argocd
spec:
  generators:
  - list:
      elements:
      - env: dev
      - env: staging
      - env: prod
  template:
    metadata:
      name: 'nginx-demo-{{env}}'
    spec:
      project: default
      source:
        repoURL: https://github.com/ton-user/argocd-demo.git
        targetRevision: HEAD
        path: 'k8s/{{env}}/'
      destination:
        server: https://kubernetes.default.svc
        namespace: '{{env}}'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
EOF

# Applique:
kubectl apply -f applicationset.yaml

# ArgoCD crée AUTOMATIQUEMENT 3 applications:
# - nginx-demo-dev (lit k8s/dev/, déploie dans namespace dev)
# - nginx-demo-staging (lit k8s/staging/, déploie dans namespace staging)
# - nginx-demo-prod (lit k8s/prod/, déploie dans namespace prod)

# Structure du repository attendue:
# k8s/
# ├── dev/
# │   ├── deployment.yaml (2 replicas, dev image)
# │   └── service.yaml
# ├── staging/
# │   ├── deployment.yaml (3 replicas, staging image)
# │   └── service.yaml
# └── prod/
#     ├── deployment.yaml (5 replicas, prod image)
#     └── service.yaml


[OK] GESTION DES REPOSITORIES GIT

# === POURQUOI GÉRER LES REPOSITORIES? ===

# Par défaut, ArgoCD peut accéder aux repositories publics
# Mais pour les repositories PRIVÉS, tu dois configurer l'accès

# Cas d'usage:
# - Repository GitHub privé
# - Repository GitLab d'entreprise
# - Serveur Git interne (Gitea, Gogs, etc.)


# === AJOUTER UN REPOSITORY PUBLIC ===

# Via l'interface web:
# 1. Settings (menu gauche) -> Repositories
# 2. Clique "+ CONNECT REPO"
# 3. Choose connection method: VIA HTTPS
# 4. Type: git
# 5. Repository URL: https://github.com/user/public-repo.git
# 6. Clique "CONNECT"

# Via CLI:
argocd repo add https://github.com/user/public-repo.git


# === AJOUTER UN REPOSITORY PRIVÉ (HTTPS + USERNAME/PASSWORD) ===

# Via l'interface web:
# 1. Settings -> Repositories -> "+ CONNECT REPO"
# 2. Choose connection method: VIA HTTPS
# 3. Type: git
# 4. Repository URL: https://github.com/user/private-repo.git
# 5. [x] Connect repo using HTTPS
# 6. Username: ton-username
# 7. Password: ton-token-github
# 8. Clique "CONNECT"

# IMPORTANT pour GitHub:
# - N'utilise PAS ton mot de passe GitHub!
# - Utilise un Personal Access Token (PAT)
# - Comment créer un PAT:
#   1. GitHub -> Settings -> Developer settings
#   2. Personal access tokens -> Tokens (classic)
#   3. Generate new token
#   4. Scopes: [x] repo (full control)
#   5. Copie le token: ghp_xxxxxxxxxxxx
#   6. Utilise ce token comme "password"

# Via CLI:
argocd repo add https://github.com/user/private-repo.git \
  --username ton-username \
  --password ghp_xxxxxxxxxxxx

# Vérifier:
argocd repo list

# Affiche:
# TYPE  NAME  REPO                                       INSECURE  OCI    LFS    CREDS  STATUS      MESSAGE
# git         https://github.com/user/private-repo.git   false     false  false  true   Successful


# === AJOUTER UN REPOSITORY PRIVÉ (SSH) ===

# Méthode plus sécurisée: Utilise des clés SSH

# Étape 1: Générer une clé SSH (si tu n'en as pas)
ssh-keygen -t ed25519 -C "argocd@mondomaine.com" -f ~/.ssh/argocd_key

# Affiche:
# Generating public/private ed25519 key pair.
# Enter passphrase (empty for no passphrase): [laisse vide]
# Your identification has been saved in /home/user/.ssh/argocd_key
# Your public key has been saved in /home/user/.ssh/argocd_key.pub

# Étape 2: Ajouter la clé publique sur GitHub/GitLab
cat ~/.ssh/argocd_key.pub

# Affiche:
# ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIxxxxxxxxxxxxxxxxxxx argocd@mondomaine.com

# Sur GitHub:
# 1. Settings -> SSH and GPG keys
# 2. New SSH key
# 3. Title: ArgoCD Server
# 4. Key: [Colle la clé publique]
# 5. Add SSH key

# Étape 3: Ajouter le repository dans ArgoCD

# Via l'interface web:
# 1. Settings -> Repositories -> "+ CONNECT REPO"
# 2. Choose connection method: VIA SSH
# 3. Repository URL: git@github.com:user/private-repo.git
# 4. SSH private key data: [Colle la clé privée]
cat ~/.ssh/argocd_key
# Copie TOUT le contenu (-----BEGIN OPENSSH PRIVATE KEY----- ... -----END OPENSSH PRIVATE KEY-----)
# 5. Clique "CONNECT"

# Via CLI:
argocd repo add git@github.com:user/private-repo.git \
  --ssh-private-key-path ~/.ssh/argocd_key


# === GÉRER LES CREDENTIALS GLOBALEMENT ===

# Au lieu d'ajouter les credentials pour chaque repository
# Tu peux les définir une fois pour plusieurs repositories

# Via l'interface web:
# 1. Settings -> Repository credentials
# 2. "+ ADD CREDENTIALS"
# 3. URL Pattern: https://github.com/*
# 4. Username: ton-username
# 5. Password: ton-token
# 6. SAVE

# Maintenant, tous les repositories github.com/* utilisent ces credentials!

# Via CLI:
argocd repocreds add https://github.com \
  --username ton-username \
  --password ton-token


# === REPOSITORY AVEC CERTIFICAT SSL PERSONNALISÉ ===

# Si ton serveur Git utilise un certificat SSL auto-signé

# Via l'interface web:
# 1. Settings -> Repositories -> "+ CONNECT REPO"
# 2. Repository URL: https://git.monentreprise.com/repo.git
# 3. [x] Skip server verification
# 4. OU: TLS client certificate (colle le certificat)
# 5. CONNECT

# Via CLI:
argocd repo add https://git.monentreprise.com/repo.git \
  --insecure-skip-server-verification


# === SUPPRIMER UN REPOSITORY ===

# Via l'interface web:
# 1. Settings -> Repositories
# 2. Trouve le repository
# 3. Clique sur les 3 points (⋮)
# 4. Remove
# 5. Confirme

# Via CLI:
argocd repo rm https://github.com/user/repo.git


[OK] SYNCHRONISATION AUTOMATIQUE (AUTO-SYNC)

# === QU'EST-CE QUE L'AUTO-SYNC? ===

# Sans auto-sync:
# - Tu push dans Git
# - ArgoCD détecte: "OutOfSync"
# - Tu dois manuellement cliquer "SYNC"
# - ArgoCD déploie

# Avec auto-sync:
# - Tu push dans Git
# - ArgoCD détecte: "OutOfSync"
# - ArgoCD synchronise AUTOMATIQUEMENT (sans ton intervention)
# - Déploiement continu!


# === ACTIVER AUTO-SYNC ===

# Méthode 1: Via l'interface web

# Pour une application existante:
# 1. Ouvre l'application (clique dessus)
# 2. Clique "APP DETAILS" (en haut)
# 3. Section "SYNC POLICY"
# 4. Clique "ENABLE AUTO-SYNC"
# 5. Une popup apparaît avec options:

# OPTIONS:
# [x] PRUNE RESOURCES
# Explications:
# - Supprime les ressources qui ne sont plus dans Git
# - Exemple: Tu supprimes service.yaml
#   -> ArgoCD supprime le Service de Kubernetes
# - Recommandé: Activer (pour cohérence totale)

# [x] SELF HEAL
# Explications:
# - Annule les modifications manuelles
# - Exemple: kubectl edit deployment
#   -> ArgoCD détecte et revient à l'état Git
# - Recommandé en prod: Activer (empêche les changements sauvages)
# - Recommandé en dev: Désactiver (permet de tester)

# Clique "OK"

# Méthode 2: Via CLI
argocd app set nginx-demo \
  --sync-policy automated \
  --auto-prune \
  --self-heal

# Vérifier:
argocd app get nginx-demo | grep "Sync Policy"
# Affiche:
# Sync Policy:        Automated (Prune, Self Heal)


# === TESTER AUTO-SYNC ===

# Fais une modification dans Git:
cd ~/argocd-demo
echo "# Test auto-sync" >> k8s/deployment.yaml
git add k8s/deployment.yaml
git commit -m "Test auto-sync"
git push origin main