# ═══════════════════════════════════════════════════════════════════
# VMWARE ULTRA-DÉTAILLÉ POUR GRANDS DÉBUTANTS
# Guide Complet Administrateur Linux/Réseaux (Ubuntu)
# Méthodologie POURQUOI / QUAND / COMMENT
# ═══════════════════════════════════════════════════════════════════

# Ce guide explore TOUTES les fonctionnalités VMware de manière exhaustive
# Chaque concept est expliqué avec:
# - POURQUOI: La raison d'être de cette fonctionnalité
# - QUAND: Les cas d'usage appropriés
# - COMMENT: L'implémentation pratique avec exemples
# - Analogies pour faciliter la compréhension
# - Erreurs courantes et comment les éviter
# - Best practices professionnelles


# ═══════════════════════════════════════════════════════════════════
# PARTIE 1: INTRODUCTION À LA VIRTUALISATION ET VMWARE
# ═══════════════════════════════════════════════════════════════════


# ═══ 1.1 QU'EST-CE QUE LA VIRTUALISATION? ═══

# POURQUOI la virtualisation existe-t-elle?
# ═════════════════════════════════════════

# PROBLÈME: Serveurs physiques traditionnels
# ──────────────────────────────────────────

# Imaginez une entreprise en 2000:
# • 1 application web -> 1 serveur physique complet
# • 1 base de données -> 1 autre serveur physique
# • 1 serveur email -> 1 autre serveur physique
# • 1 serveur fichiers -> encore 1 serveur
# -> 4 applications = 4 serveurs physiques!

# PROBLÈMES:
# [X] Coût énorme (serveur = 2000-10000€)
# [X] Espace datacenter (4 racks)
# [X] Électricité (4 alimentations)
# [X] Refroidissement (climatisation puissante)
# [X] Maintenance (4 machines à gérer)
# [X] Sous-utilisation (serveur web utilise 10% CPU seulement!)
# [X] Temps déploiement (commande serveur = 2-4 semaines)
# [X] Difficulté migration (déplacer serveur physique = cauchemar)

# Exemple concret:
# Serveur web: CPU 5%, RAM 20%, Disque 10%
# -> 95% des ressources GASPILLÉES!


# SOLUTION: Virtualisation
# ════════════════════════

# Sur 1 SEUL serveur physique puissant:
# • Machine Virtuelle 1: Serveur web
# • Machine Virtuelle 2: Base de données
# • Machine Virtuelle 3: Email
# • Machine Virtuelle 4: Fichiers
# -> 4 applications sur 1 serveur physique!

# AVANTAGES:
# [OK] Coût réduit (1 serveur au lieu de 4 = économie 75%)
# [OK] Espace réduit (1 rack au lieu de 4)
# [OK] Électricité réduite (1 alimentation)
# [OK] Meilleure utilisation (CPU 80% au lieu de 10%)
# [OK] Déploiement rapide (nouvelle VM = 5 minutes!)
# [OK] Snapshot/Backup facile
# [OK] Migration simple (déplacer fichier VM)
# [OK] Isolation (crash VM1 n'affecte pas VM2)

# Exemple concret:
# 1 serveur physique (64 cores, 512GB RAM):
# • 10 VMs moyennes (chacune 4 cores, 32GB RAM)
# • Utilisation totale: CPU 70%, RAM 85%
# -> Optimisation ressources!


# ANALOGIE: Appartements vs Maisons individuelles
# ═══════════════════════════════════════════════

# SANS virtualisation (Maisons individuelles):
# ────────────────────────────────────────────
# • 1 personne = 1 maison complète (terrain, toit, murs)
# • 4 personnes = 4 maisons (4 terrains, 4 toits, 4 systèmes chauffage)
# • Coût énorme, beaucoup d'espace
# • Chaque maison sous-utilisée (pièces vides)

# AVEC virtualisation (Immeuble d'appartements):
# ──────────────────────────────────────────────
# • 1 immeuble = 10 appartements
# • 1 fondation partagée (= serveur physique)
# • 1 toit partagé (= alimentation)
# • 10 espaces indépendants (= 10 VMs)
# • Coût divisé, optimisation espace
# • Chaque appartement isolé (voisin bruyant n'entre pas chez vous)


# QU'EST-CE qu'une Machine Virtuelle (VM)?
# ════════════════════════════════════════

# VM = Ordinateur logiciel à l'intérieur d'un ordinateur physique

# Composants VM:
# • CPU virtuel (vCPU): Partage du CPU physique
# • RAM virtuelle: Allocation mémoire dédiée
# • Disque virtuel: Fichier .vmdk sur disque physique
# • Carte réseau virtuelle: Interface réseau logicielle
# • Carte graphique virtuelle
# • Ports USB virtuels
# • Tout comme un PC réel, mais en logiciel!

# Exemple:
# Serveur physique: 32 cores, 256GB RAM, 2TB SSD
# 
# VM1 (Serveur Web):
# - 4 vCPUs (utilise 4 cores physiques)
# - 8GB RAM (alloué de 256GB)
# - 100GB disque (fichier ubuntu-web.vmdk = 100GB)
# - 1 carte réseau (vmnic0)
# 
# VM2 (Base de données):
# - 8 vCPUs
# - 32GB RAM
# - 500GB disque
# - 1 carte réseau


# TYPES DE VIRTUALISATION:
# ═══════════════════════

# 1. VIRTUALISATION COMPLÈTE (Full Virtualization)
#    ──────────────────────────────────────────────
#    VM ne sait PAS qu'elle est virtualisée
#    OS invité non modifié
#    Exemple: VMware ESXi, Hyper-V
#    Performance: Excellente (quasi-native)

# 2. PARAVIRTUALISATION
#    ──────────────────
#    VM sait qu'elle est virtualisée
#    OS invité modifié pour optimisation
#    Exemple: Xen, ancien KVM
#    Performance: Très bonne mais moins utilisée

# 3. CONTENEURISATION
#    ────────────────
#    Partage noyau OS hôte
#    Pas de VM complète, juste isolation processus
#    Exemple: Docker, LXC
#    Performance: Native (léger)
#    Limitation: Même OS que l'hôte


# ═══ 1.2 QU'EST-CE QUE VMWARE? ═══

# VMWARE = Leader mondial virtualisation depuis 1998

# HISTOIRE VMWARE:
# ═══════════════

# 1998: Fondation VMware par Diane Greene et Mendel Rosenblum
# 1999: VMware Workstation 1.0 (virtualisation desktop)
# 2001: VMware ESX 1.0 (virtualisation serveur)
# 2004: Rachat par EMC Corporation
# 2007: Introduction en bourse
# 2009: VMware vSphere (suite complète)
# 2015: Spin-off d'EMC (indépendant)
# 2022: Rachat par Broadcom (61 milliards $)
# 2024: VMware = Standard industrie virtualisation


# PRODUITS VMWARE (Écosystème complet):
# ════════════════════════════════════

# 1. VMWARE WORKSTATION (Desktop - Windows/Linux)
#    ─────────────────────────────────────────────
#    • Pour développeurs, testeurs, étudiants
#    • VMs sur poste de travail
#    • Prix: ~300€ licence perpétuelle
#    • Interface graphique complète
#    • Idéal pour: Labs, tests, développement

# 2. VMWARE PLAYER/FUSION (Desktop gratuit/simple)
#    ──────────────────────────────────────────────
#    • Version gratuite (usage personnel)
#    • Fusion = version macOS
#    • Fonctionnalités limitées
#    • Parfait débutants

# 3. VMWARE ESXi (Serveur - Hyperviseur Type 1)
#    ──────────────────────────────────────────
#    • Hyperviseur bare-metal (directement sur hardware)
#    • Version gratuite disponible (limitée)
#    • Production datacenter
#    • Pas d'OS hôte (ESXi = OS minimal)
#    • Performance maximale

# 4. VMWARE vSphere (Suite entreprise)
#    ─────────────────────────────────
#    • ESXi + vCenter Server
#    • Gestion centralisée multiple ESXi
#    • HA (High Availability)
#    • DRS (Distributed Resource Scheduler)
#    • vMotion (migration à chaud)
#    • Prix: Plusieurs milliers € par CPU

# 5. VMWARE vSAN (Stockage software-defined)
#    ───────────────────────────────────────
#    • Stockage distribué sur cluster ESXi
#    • Alternative SAN traditionnel

# 6. VMWARE NSX (Réseau software-defined)
#    ────────────────────────────────────
#    • Virtualisation réseau
#    • Firewall distribué
#    • Load balancing

# 7. VMWARE HORIZON (VDI - Virtual Desktop Infrastructure)
#    ──────────────────────────────────────────────────────
#    • Bureaux virtuels
#    • Desktop as a Service


# POURQUOI choisir VMware plutôt qu'un autre?
# ═══════════════════════════════════════════

# ALTERNATIVES:
# • Microsoft Hyper-V (gratuit Windows Server)
# • Proxmox VE (open-source, gratuit)
# • KVM (Linux natif)
# • Oracle VirtualBox (gratuit)
# • Citrix XenServer

# AVANTAGES VMWARE:
# [OK] Leader marché (70% datacenter entreprise)
# [OK] Écosystème complet (tous besoins couverts)
# [OK] Performance excellente
# [OK] Support professionnel 24/7
# [OK] Documentation exhaustive
# [OK] Communauté énorme (forums, blogs, Youtube)
# [OK] Certifications reconnues (VCP, VCAP)
# [OK] Compatibilité hardware maximale
# [OK] Features avancées (vMotion, DRS, HA)
# [OK] Intégration cloud (AWS, Azure, Google)

# INCONVÉNIENTS VMWARE:
# [X] Prix élevé (vSphere = cher)
# [X] Propriétaire (pas open-source)
# [X] Complexité (courbe apprentissage)
# [X] Vendor lock-in


# QUAND utiliser VMware?
# ═════════════════════

# [OK] PARFAIT POUR:
# • Entreprises production (critiques business)
# • Datacenters (100+ serveurs)
# • Cloud privé
# • Environnements mixtes (Windows/Linux)
# • Besoin features avancées (HA, DRS, vMotion)
# • Budget disponible
# • Support 24/7 requis
# • Certifications staff IT

# [X] ALTERNATIVES MEILLEURES:
# • Petite entreprise budget limité -> Proxmox, Hyper-V
# • Environnement 100% Linux -> KVM
# • Usage desktop personnel -> VirtualBox
# • Conteneurs modernes -> Docker/Kubernetes


# ═══ 1.3 CONCEPTS FONDAMENTAUX VIRTUALISATION ═══

# HYPERVISEUR (Hypervisor)
# ════════════════════════

# DÉFINITION:
# Logiciel créant et gérant machines virtuelles
# Couche entre hardware physique et VMs

# TYPES D'HYPERVISEURS:

# TYPE 1 (Bare-Metal) - PRODUCTION
# ────────────────────────────────
# Installé directement sur hardware (pas d'OS hôte)
# 
# [VMs]
#   v
# [Hyperviseur Type 1: ESXi, Hyper-V, Xen]
#   v
# [Hardware physique: CPU, RAM, Disque]
# 
# AVANTAGES:
# [OK] Performance maximale (accès direct hardware)
# [OK] Sécurité (surface attaque réduite)
# [OK] Stabilité
# [OK] Optimisé virtualisation
# 
# EXEMPLES:
# • VMware ESXi <- Nous couvrirons en détail
# • Microsoft Hyper-V (Windows Server)
# • Citrix XenServer
# • Proxmox VE (KVM-based)


# TYPE 2 (Hosted) - DESKTOP/DÉVELOPPEMENT
# ───────────────────────────────────────
# Installé sur OS existant (Windows, Linux, macOS)
# 
# [VMs]
#   v
# [Hyperviseur Type 2: Workstation, VirtualBox]
#   v
# [OS Hôte: Windows 11, Ubuntu, macOS]
#   v
# [Hardware physique]
# 
# AVANTAGES:
# [OK] Facile installer (comme application normale)
# [OK] Utilisation simultanée (OS hôte + VMs)
# [OK] Débutant-friendly
# [OK] Pas besoin dédier machine
# 
# INCONVÉNIENTS:
# [X] Performance réduite (overhead OS hôte)
# [X] Moins stable (dépend OS hôte)
# [X] Pas pour production critique
# 
# EXEMPLES:
# • VMware Workstation Pro (Windows/Linux)
# • VMware Fusion (macOS)
# • Oracle VirtualBox
# • Parallels Desktop (macOS)


# COMPARAISON:
# ──────────

# Critère          | Type 1 (ESXi)    | Type 2 (Workstation)
# ─────────────────|───────────────---|─────────────────────
# Performance      | 95-98% native    | 80-90% native
# Installation     | Dédiée           | Sur OS existant
# Utilisation      | Production       | Dev/Test
# Stabilité        | Excellente       | Dépend OS hôte
# Coût             | Élevé            | Moyen
# Complexité       | Moyenne-Haute    | Basse
# Gestion          | vCenter/CLI      | GUI simple


# OS HÔTE vs OS INVITÉ (Guest)
# ════════════════════════════

# OS HÔTE (Host OS):
# • OS sur machine physique (Type 2 uniquement)
# • Windows 11, Ubuntu 24.04, macOS
# • Exécute hyperviseur (Workstation)
# • A accès direct hardware

# OS INVITÉ (Guest OS):
# • OS dans machine virtuelle
# • Ubuntu Server, Windows Server, CentOS, etc.
# • Ne voit que hardware virtuel
# • Isolé des autres VMs


# RESSOURCES MATÉRIELLES (Hardware Resources)
# ═══════════════════════════════════════════

# CPU (Processeur)
# ───────────────
# • CPU physique: Intel Xeon, AMD EPYC
# • Cores physiques: 8, 16, 32, 64 cores
# • Threads: Hyper-Threading (2 threads/core)
# • vCPU: CPU virtuel alloué à VM
# 
# Exemple:
# Serveur: Intel Xeon 32 cores (64 threads HT)
# VM1: 4 vCPUs (utilise 4 threads)
# VM2: 8 vCPUs (utilise 8 threads)
# 
# RÈGLE: Ne pas sur-allouer massivement
# Max recommandé: 4:1 (4 vCPUs pour 1 core physique)

# RAM (Mémoire)
# ────────────
# • RAM physique: 64GB, 128GB, 256GB, 512GB, 1TB
# • RAM VM: Allocation stricte (pas de sur-allocation safe)
# 
# Exemple:
# Serveur: 256GB RAM physique
# VM1: 16GB (réservé)
# VM2: 32GB (réservé)
# VM3: 8GB (réservé)
# Total utilisé: 56GB
# Disponible: 200GB
# 
# [ATTENTION] ATTENTION: Sur-allocation RAM = swapping = lenteur!

# DISQUE (Storage)
# ───────────────
# • Disque physique: SSD NVMe, SAS, SATA
# • RAID: 1, 5, 6, 10 (redondance)
# • SAN/NAS: Stockage réseau (iSCSI, NFS, Fibre Channel)
# • Disque VM: Fichier .vmdk (virtual disk)
# 
# Types disques VM:
# • Thick Provisioned Eager Zeroed (meilleure performance)
# • Thick Provisioned Lazy Zeroed (bon compromis)
# • Thin Provisioned (économie espace, attention sur-allocation)

# RÉSEAU (Network)
# ───────────────
# • NIC physique: Carte réseau 1Gbps, 10Gbps, 25Gbps
# • vNIC: Carte réseau virtuelle VM
# • vSwitch: Switch virtuel (relie VMs)
# • Port Group: VLAN sur vSwitch


# FICHIERS MACHINE VIRTUELLE
# ══════════════════════════

# VM = Ensemble de fichiers sur disque

# FICHIERS PRINCIPAUX:

# .vmx (VM Configuration)
# ──────────────────────
# • Fichier texte configuration VM
# • Hardware virtuel (CPU, RAM, réseau)
# • Options boot, BIOS
# • Équivalent: "specs PC" (4 cores, 8GB RAM, etc.)
# 
# Exemple: ubuntu-server.vmx
config.version = "8"
virtualHW.version = "21"
numvcpus = "4"
memsize = "8192"
displayName = "Ubuntu Server 22.04"

# .vmdk (Virtual Disk)
# ───────────────────
# • Disque dur virtuel
# • Contient OS, applications, données
# • Types: flat (données) + descriptor (config)
# • Taille: Fixe ou dynamique
# 
# Exemple: ubuntu-server.vmdk (descriptor)
#          ubuntu-server-flat.vmdk (données réelles)

# .nvram (BIOS Settings)
# ─────────────────────
# • Configuration BIOS/EFI
# • Boot order, paramètres hardware

# .vmsd (Snapshot Data)
# ────────────────────
# • Informations snapshots
# • Arbre snapshots

# .vmsn (Snapshot State)
# ─────────────────────
# • État mémoire snapshot
# • Registres CPU

# .vmss (Suspended State)
# ──────────────────────
# • État VM suspendue
# • Contenu RAM sauvegardé

# -delta.vmdk (Snapshot Disk)
# ──────────────────────────
# • Différences depuis snapshot
# • Chaîne: base.vmdk -> snap1-delta.vmdk -> snap2-delta.vmdk


# ═══════════════════════════════════════════════════════════════════
# PARTIE 2: VMWARE WORKSTATION - INSTALLATION ET CONFIGURATION
# ═══════════════════════════════════════════════════════════════════


# ═══ 2.1 CHOISIR ENTRE WORKSTATION PRO ET PLAYER ═══

# VMWARE WORKSTATION PRO (Payant)
# ═══════════════════════════════

# PRIX: ~300€ licence perpétuelle (1 PC)

# FONCTIONNALITÉS:
# [OK] VMs multiples simultanées (illimité)
# [OK] Snapshots multiples (arbre complet)
# [OK] Clonage VMs (linked, full)
# [OK] Réseau avancé (custom, host-only, NAT)
# [OK] Partage dossiers hôte/guest
# [OK] Remote connections
# [OK] Enregistrement vidéo VM
# [OK] Support USB 3.0/3.1
# [OK] Encrypted VMs (sécurité)
# [OK] Support commercial
# [OK] Intégration vSphere
# [OK] RestAPI

# QUAND UTILISER:
# • Professionnel IT
# • Développeur (tests multi-OS)
# • Formation/Labs complexes
# • Besoin snapshots avancés
# • Environnements imbriqués (VM dans VM)


# VMWARE WORKSTATION PLAYER (Gratuit usage perso)
# ═══════════════════════════════════════════════

# PRIX: Gratuit usage personnel, ~150€ commercial

# FONCTIONNALITÉS:
# [OK] 1 VM à la fois
# [OK] 1 snapshot par VM (pas d'arbre)
# [X] Pas de clonage
# [X] Réseau limité (NAT, bridged basique)
# [X] Pas de remote connections
# [X] Pas d'encryption

# QUAND UTILISER:
# • Étudiant débutant
# • Usage occasionnel
# • Budget limité
# • 1-2 VMs maximum
# • Besoins basiques


# ALTERNATIVES GRATUITES:
# ══════════════════════

# ORACLE VIRTUALBOX (Open-source, 100% gratuit)
# ─────────────────────────────────────────────
# [OK] Gratuit commercial
# [OK] Multi-plateformes (Win/Lin/Mac)
# [OK] Snapshots multiples
# [OK] Clonage VMs
# [OK] Réseau avancé
# [X] Performance inférieure VMware
# [X] Moins stable
# [X] Support communauté seulement

# KVM (Linux natif)
# ────────────────
# [OK] Intégré Linux kernel
# [OK] Performance excellente
# [OK] Gratuit
# [X] Linux seulement
# [X] Courbe apprentissage

# PROXMOX VE (Open-source Type 1)
# ───────────────────────────────
# [OK] Hyperviseur bare-metal gratuit
# [OK] Web interface
# [OK] Clustering
# [X] Nécessite serveur dédié


# ═══ 2.2 PRÉREQUIS MATÉRIELS ET LOGICIELS ═══

# CONFIGURATION MINIMALE (Workstation)
# ════════════════════════════════════

# [ATTENTION] ATTENTION: "Minimal" = pour 1 VM légère seulement!

# CPU:
# • Processeur 64-bit Intel/AMD
# • 2 cores minimum
# • Virtualisation activée (Intel VT-x ou AMD-V)

# RAM:
# • 4GB minimum (OS hôte + 1 VM)
# • Répartition: 2GB hôte + 2GB VM

# DISQUE:
# • 5GB pour Workstation
# • 20-50GB par VM
# • SSD recommandé (performance)

# OS HÔTE:
# • Windows 10/11 (64-bit)
# • Ubuntu 20.04/22.04/24.04
# • Autres Linux récents


# CONFIGURATION RECOMMANDÉE (Usage professionnel)
# ═══════════════════════════════════════════════

# CPU:
# • Intel Core i7/i9 ou AMD Ryzen 7/9
# • 6+ cores (8+ idéal)
# • Virtualisation + VT-d/AMD-Vi (passthrough)

# RAM:
# • 16GB minimum (32GB recommandé)
# • Répartition exemple (32GB):
#   - 8GB Windows hôte
#   - 8GB VM1 (Ubuntu Server)
#   - 8GB VM2 (Windows Server)
#   - 8GB VM3 (Test)

# DISQUE:
# • SSD NVMe 500GB+ (VMs rapides)
# • Ou: SSD 256GB (OS hôte + Workstation)
#      + HDD 1TB (stockage VMs)

# RÉSEAU:
# • Carte réseau Gigabit Ethernet
# • Ou WiFi AC/AX (moins optimal)


# VÉRIFIER SUPPORT VIRTUALISATION
# ═══════════════════════════════

# WINDOWS: Vérifier VT-x/AMD-V
# ───────────────────────────

# Méthode 1: Task Manager
# 1. Ctrl+Shift+Esc (Task Manager)
# 2. Onglet "Performance"
# 3. CPU
# 4. Chercher "Virtualization: Enabled"
# 
# Si "Disabled" -> Activer dans BIOS

# Méthode 2: SystemInfo
cmd
systeminfo | findstr /i "Hyper"

# Résultat attendu:
Hyper-V Requirements: VM Monitor Mode Extensions: Yes
                      Virtualization Enabled In Firmware: Yes

# Méthode 3: CPU-Z (logiciel tiers)
# Instructions supportées: VT-x ou AMD-V


# LINUX: Vérifier VT-x/AMD-V
# ─────────────────────────

# Vérifier flags CPU:
grep -E '(vmx|svm)' /proc/cpuinfo

# Si résultat:
# vmx = Intel VT-x [OK]
# svm = AMD-V [OK]
# Rien = Virtualisation désactivée [X]

# Vérifier KVM:
lscpu | grep Virtualization

# Résultat:
Virtualization:      VT-x    (Intel)
# ou
Virtualization:      AMD-V   (AMD)


# ACTIVER VIRTUALISATION DANS BIOS
# ════════════════════════════════

# ÉTAPES GÉNÉRALES:
# 1. Redémarrer PC
# 2. Appuyer F2/F10/Del (dépend fabricant) pendant boot
# 3. Aller dans "Advanced" ou "CPU Configuration"
# 4. Chercher option:
#    • Intel: "Intel VT-x", "Virtualization Technology"
#    • AMD: "AMD-V", "SVM Mode"
# 5. Mettre sur "Enabled"
# 6. Sauvegarder et quitter (F10)

# FABRICANTS SPÉCIFIQUES:

# DELL:
# • Touche: F2
# • Menu: Virtualization Support
# • Option: Enable Intel Virtualization Technology

# HP:
# • Touche: F10 ou Esc
# • Menu: System Configuration -> Virtualization Technology
# • Option: Enabled

# LENOVO:
# • Touche: F1 ou F2
# • Menu: Security -> Virtualization
# • Option: Intel (R) Virtualization Technology: Enabled

# ASUS:
# • Touche: F2 ou Del
# • Menu: Advanced -> CPU Configuration
# • Option: Intel Virtualization Technology: Enabled


# DÉSACTIVER HYPER-V (Windows)
# ════════════════════════════

# [ATTENTION] IMPORTANT: Hyper-V et VMware incompatibles!

# Si Hyper-V activé -> VMware ne peut pas utiliser VT-x

# VÉRIFIER SI HYPER-V ACTIF:
# ─────────────────────────

# PowerShell (Admin):
Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All

# Si "State: Enabled" -> Désactiver


# DÉSACTIVER HYPER-V:
# ──────────────────

# Méthode 1: PowerShell (Admin)
Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All

# Méthode 2: Panneau de configuration
# 1. Panneau de configuration
# 2. Programmes -> Activer/Désactiver fonctionnalités Windows
# 3. Décocher "Hyper-V"
# 4. OK
# 5. Redémarrer

# Méthode 3: CMD (Admin) - Désactiver Hypervisor
bcdedit /set hypervisorlaunchtype off

# Redémarrer PC obligatoire!

# RÉACTIVER si besoin:
bcdedit /set hypervisorlaunchtype auto


# ═══ 2.3 TÉLÉCHARGER VMWARE WORKSTATION ═══

# TÉLÉCHARGEMENT OFFICIEL:
# ════════════════════════

# WINDOWS:
# ───────
# URL: https://www.vmware.com/products/workstation-pro/workstation-pro-evaluation.html

# 1. Aller sur site VMware
# 2. Cliquer "Download Now"
# 3. Choisir version:
#    • Workstation Pro (trial 30 jours puis payant)
#    • Workstation Player (gratuit usage perso)
# 
# Fichier téléchargé:
# VMware-workstation-full-17.5.0-22583795.exe
# Taille: ~600MB

# LINUX:
# ─────
# Fichier téléchargé:
# VMware-Workstation-Full-17.5.0-22583795.x86_64.bundle
# Taille: ~600MB


# VERSIONS VMWARE WORKSTATION:
# ════════════════════════════

# Historique versions importantes:

# Version 17.x (Actuelle - 2023-2024)
# ──────────────────────────────────
# • Support Windows 11, Ubuntu 24.04
# • Support vTPM 2.0 (requis Windows 11)
# • USB 3.2 support
# • Virtual Hardware 21

# Version 16.x (2020-2022)
# ───────────────────────
# • Support Windows 10 20H2
# • Conteneurs intégration
# • Virtual Hardware 19

# Version 15.x (2019-2020)
# ───────────────────────
# • DirectX 11 support
# • Virtual Hardware 18

# Version 12.x (2015-2016)
# ───────────────────────
# • Windows 10 initial support
# • Virtual Hardware 12


# OBTENIR LICENCE (Options):
# ═════════════════════════

# OPTION 1: Trial 30 jours (Gratuit)
# ──────────────────────────────────
# • Fonctionnalités complètes
# • Après 30 jours -> Mode Player (limité)
# • Idéal pour tests/formation

# OPTION 2: Achat licence individuelle
# ────────────────────────────────────
# • ~300€ licence perpétuelle
# • 1 PC uniquement
# • Mises à jour majeures payantes

# OPTION 3: Abonnement entreprise
# ───────────────────────────────
# • Licence volume (10+ utilisateurs)
# • Support inclus
# • Mises à jour incluses

# OPTION 4: Académique (Étudiants/Profs)
# ──────────────────────────────────────
# • Réduction 50-80%
# • VMware Academic Program
# • Justificatif étudiant requis

# OPTION 5: Workstation Player (Gratuit)
# ──────────────────────────────────────
# • Usage personnel non-commercial
# • Fonctionnalités limitées
# • Aucune clé requise


# ═══ 2.4 INSTALLER VMWARE WORKSTATION (WINDOWS) ═══

# INSTALLATION PAS À PAS:
# ══════════════════════

# ÉTAPE 1: Lancer installateur
# ────────────────────────────
# 1. Double-cliquer VMware-workstation-full-17.5.0.exe
# 2. UAC prompt -> Cliquer "Oui" (droits admin)
# 3. Écran "Welcome" -> Next

# ÉTAPE 2: Accepter licence
# ────────────────────────
# 1. Lire EULA (End User License Agreement)
# 2. Cocher "I accept the terms"
# 3. Next

# ÉTAPE 3: Type d'installation
# ────────────────────────────
# Options:
# • [[OK]] Enhanced Keyboard Driver
#       -> Recommandé (meilleur support clavier dans VMs)
# 
# • [[OK]] Add VMware Workstation console tools
#       -> Ajoute vmrun.exe au PATH (ligne de commande)
# 
# Next

# ÉTAPE 4: Expérience utilisateur
# ───────────────────────────────
# • [ ] Check for product updates on startup
#       -> Décocher si pas d'internet ou contrôle updates
# 
# • [ ] Join VMware Customer Experience Program
#       -> Décocher (télémétrie)
# 
# Next

# ÉTAPE 5: Raccourcis
# ──────────────────
# • [[OK]] Desktop
# • [[OK]] Start Menu Programs
# 
# Next

# ÉTAPE 6: Prêt à installer
# ─────────────────────────
# • Vérifier résumé
# • Install (commence copie fichiers)
# 
# Durée: 2-5 minutes
# 
# Progression:
# [████████████████████] 100%
# Installing VMware Workstation...

# ÉTAPE 7: Fin installation
# ────────────────────────
# • "Installation was successful"
# • [[OK]] License: Enter license key now (optionnel)
# • Finish
# 
# -> Redémarrage optionnel (recommandé)


# PREMIER LANCEMENT:
# ═════════════════

# 1. Démarrer VMware Workstation
#    • Icône Desktop
#    • Ou: Menu Démarrer -> VMware Workstation
# 
# 2. Écran Licence
#    ┌─────────────────────────────────────┐
#    │ VMware Workstation Pro             │
#    │                                     │
#    │ Enter License Key:                  │
#    │ [_____-_____-_____-_____-_____]    │
#    │                                     │
#    │ [Evaluate] [Enter Key]             │
#    └─────────────────────────────────────┘
# 
#    Options:
#    • "Evaluate" -> Trial 30 jours
#    • "Enter Key" -> Si vous avez acheté licence
#    • "Use Player" -> Mode gratuit limité

# 3. Interface principale s'ouvre!


# VÉRIFIER INSTALLATION:
# ═════════════════════

# Windows:

# Vérifier version:
# Help -> About VMware Workstation
# Affiche: "VMware Workstation 17.5.0 build-22583795"

# Vérifier services:
# Services.msc (Win+R)
# Chercher:
# • VMware Authorization Service (Running)
# • VMware DHCP Service (Running)
# • VMware NAT Service (Running)
# • VMware USB Arbitration Service (Running)

# Tous doivent être "Running" (Démarré)


# ═══ 2.5 INSTALLER VMWARE WORKSTATION (LINUX) ═══

# PRÉREQUIS LINUX:
# ═══════════════

# Ubuntu 22.04/24.04:
sudo apt update
sudo apt install -y build-essential gcc make linux-headers-$(uname -r)

# Fedora:
sudo dnf install -y gcc kernel-devel kernel-headers make

# Arch Linux:
sudo pacman -S linux-headers base-devel


# INSTALLATION:
# ════════════

# Rendre fichier exécutable:
chmod +x VMware-Workstation-Full-17.5.0-22583795.x86_64.bundle

# Installer (root requis):
sudo ./VMware-Workstation-Full-17.5.0-22583795.x86_64.bundle

# Ou avec paramètres:
sudo ./VMware-Workstation-Full-17.5.0-22583795.x86_64.bundle \
  --console \
  --required \
  --eulas-agreed

# Options:
# --console: Mode texte (pas de GUI installeur)
# --required: Installer composants obligatoires seulement
# --eulas-agreed: Accepter EULAs automatiquement


# ASSISTANT INSTALLATION:
# ══════════════════════

# 1. Écran bienvenue
# Do you accept? (yes/no)
yes

# 2. Chemin installation
# Install path: [/usr/lib/vmware]
# (Enter pour défaut)

# 3. Créer certificats SSL
# Would you like to create SSL certificates? (yes/no)
yes

# 4. Integration système
# Do you want to check for updates? (yes/no)
no

# 5. Customer Experience Program
# Join program? (yes/no)
no

# 6. Compilation modules kernel
# Building modules...
# [████████████████████] 100%
# 
# Modules compilés:
# • vmmon (VMware monitor)
# • vmnet (VMware networking)
# • vmci (Virtual Machine Communication Interface)
# • vsock (Virtual Socket)

# 7. Fin installation
# Installation complete!


# LANCER VMWARE:
# ═════════════

# Ligne de commande:
vmware &

# Ou menu applications:
# Applications -> VMware Workstation


# MODULES KERNEL:
# ══════════════

# Lister modules chargés:
lsmod | grep vm

# Résultat attendu:
vmmon                 118784  0
vmnet                  53248  13
vmci                   77824  2
vsock_vmci_transport    32768  0

# Si modules pas chargés:
sudo modprobe vmmon
sudo modprobe vmnet


# PROBLÈMES COURANTS LINUX:
# ════════════════════════

# ERREUR: "Could not compile vmmon module"
# ───────────────────────────────────────

# CAUSE: Headers kernel manquants ou version mismatch

# SOLUTION:
# Vérifier version kernel:
uname -r
# Ex: 6.5.0-28-generic

# Installer headers correspondants:
sudo apt install linux-headers-$(uname -r)

# Recompiler modules:
sudo vmware-modconfig --console --install-all


# ERREUR: "vmmon failed to load"
# ──────────────────────────────

# CAUSE: Secure Boot activé (bloque modules non signés)

# SOLUTION 1: Désactiver Secure Boot (BIOS)
# Solution 2: Signer modules (complexe)

# Vérifier Secure Boot:
mokutil --sb-state

# Si "SecureBoot enabled":
# -> Redémarrer, entrer BIOS, désactiver Secure Boot


# ERREUR: Permission denied
# ────────────────────────

# CAUSE: User pas dans groupe correct

# SOLUTION:
sudo usermod -aG dialout $USER
sudo usermod -aG vboxusers $USER

# Logout/Login pour appliquer


# ═══ 2.6 INTERFACE VMWARE WORKSTATION ═══

# DÉCOUVERTE INTERFACE PRINCIPALE:
# ═══════════════════════════════

# Layout global:
# ┌─────────────────────────────────────────────────────────┐
# │ [File] [Edit] [View] [VM] [Tabs] [Help]    [[RECHERCHE]]  [[CONFIG]]  │ <- Menu Bar
# ├─────────────────────────────────────────────────────────┤
# │ [[DOSSIER]] [+] [[CONFIG]] [[BLACK_RIGHT-POINTING_TRIANGLE]] [[DOUBLE_VERTICAL_BAR]] [[BLACK_SQUARE_FOR_STOP]] [[CAMERA_WITH_FLASH]] [[SYNC]]                 │ <- Toolbar
# ├─────────────────┬───────────────────────────────────────┤
# │                 │                                       │
# │  [DOSSIER] My Computer │    ┌─ Tab: Ubuntu Server ──┐        │
# │  [DOSSIER] Favorites   │    │                         │        │
# │                 │    │   [Console Display]     │        │
# │  [ECRAN] VM1: Ubuntu │    │                         │        │
# │  [ECRAN] VM2: Windows│    │   [Virtual Screen]      │        │
# │  [ECRAN] VM3: CentOS │    │                         │        │
# │                 │    │                         │        │
# │                 │    └─────────────────────────┘        │
# │  Library (VMs)  │           VM Display Area             │
# │                 │                                       │
# │                 │                                       │
# │                 │                                       │
# └─────────────────┴───────────────────────────────────────┘
#   Sidebar            Main Workspace


# MENU BAR (Barre de menus):
# ═════════════════════════

# FILE
# ────
# • New Virtual Machine: Créer nouvelle VM (wizard)
# • Open: Ouvrir VM existante (.vmx)
# • Close Tab: Fermer onglet VM actuel
# • Scan for Virtual Machines: Chercher VMs sur disque
# • Connect to Server: vSphere/ESXi distant
# • Export to OVF: Exporter VM (format universel)
# • Preferences: Paramètres globaux Workstation

# EDIT
# ────
# • Preferences: Paramètres (raccourci)
# • Virtual Network Editor: Configuration réseau virtuel

# VIEW
# ────
# • Customize: Personnaliser toolbar
# • Full Screen: Plein écran VM
# • Unity: Mode intégration (Windows guest dans Windows host)
# • Console View: Vue console VM
# • Fit Guest Now: Ajuster résolution guest

# VM
# ──
# • Power: On/Off/Suspend/Reset VM
# • Removable Devices: CD/DVD, USB
# • Snapshot: Prendre snapshot
# • Settings: Configuration matérielle VM
# • Install VMware Tools: Installer drivers optimisés
# • Send Ctrl+Alt+Del: Envoyer combinaison clavier

# TABS
# ────
# • New Tab: Nouvel onglet
# • All Tabs: Voir tous onglets ouverts

# HELP
# ────
# • Help Contents: Documentation
# • About: Version Workstation


# TOOLBAR (Barre d'outils):
# ════════════════════════

# [[DOSSIER]] Open VM
#      Ouvrir VM existante

# [+] Create New VM
#      Lancer wizard création VM

# [[CONFIG]] Edit VM Settings
#      Configurer hardware VM sélectionnée

# [[BLACK_RIGHT-POINTING_TRIANGLE]] Power On
#      Démarrer VM

# [[DOUBLE_VERTICAL_BAR]] Suspend
#      Mettre en veille (sauvegarde état RAM)

# [[BLACK_SQUARE_FOR_STOP]] Power Off
#      Éteindre VM

# [[CAMERA_WITH_FLASH]] Take Snapshot
#      Prendre snapshot état actuel

# [[SYNC]] Revert to Snapshot
#      Restaurer snapshot précédent

# [[UTILISATEURS]] View Multiple VMs
#      Afficher plusieurs VMs en mosaïque


# SIDEBAR (Panneau latéral):
# ═════════════════════════

# MY COMPUTER
# ──────────
# • Machine physique locale
# • Informations système hôte:
#   - OS: Windows 11 Pro
#   - CPU: Intel Core i7-12700K (12 cores)
#   - RAM: 32GB
# • Resource utilization

# FAVORITES
# ────────
# • VMs épinglées (accès rapide)
# • Drag & drop VMs ici pour favoris

# LIBRARY
# ───────
# Liste de toutes VMs:
# 
# [ECRAN] Ubuntu Server 22.04
#    [GRAPHIQUE] Status: Powered Off
#    [SAUVEGARDE] 20GB disk
# 
# [ECRAN] Windows 11 Pro
#    [GRAPHIQUE] Status: Running
#    [SAUVEGARDE] 60GB disk
# 
# [ECRAN] CentOS 9 Stream
#    [GRAPHIQUE] Status: Suspended
#    [SAUVEGARDE] 40GB disk

# Clic droit VM -> Menu contextuel:
# • Open
# • Power On/Off
# • Settings
# • Snapshot Manager
# • Clone
# • Delete from Disk


# MAIN WORKSPACE (Zone de travail):
# ════════════════════════════════

# TABS (Onglets):
# ──────────────
# Chaque VM ouverte = 1 onglet
# Switch facilement entre VMs
# 
# [Ubuntu Server] [Windows 11] [CentOS] [+]
#       ^ active

# CONSOLE DISPLAY:
# ───────────────
# Affichage écran VM (comme moniteur physique)
# • Clavier/souris capturés quand clic dans fenêtre
# • Ctrl+Alt pour libérer curseur (par défaut)
# • Résolution auto-ajustée

# STATUS BAR (Bas de fenêtre):
# ───────────────────────────
# [[DISQUE] CD: Disconnected] [[PLUGIN] Net: Connected] [[RAPIDE] 4 vCPU] [[SAUVEGARDE] 8GB RAM]

# Informations temps réel:
# • Périphériques connectés (CD, USB, réseau)
# • Ressources allouées
# • Network traffic (^v KB/s)


# ═══ 2.7 PRÉFÉRENCES WORKSTATION (ESSENTIELLES) ═══

# Edit -> Preferences (ou Ctrl+P)

# ONGLET "WORKSPACE":
# ══════════════════

# Default location for virtual machines:
# C:\Users\VotreNom\Documents\Virtual Machines
# 
# -> Changer si disque système petit:
#    D:\VMs  (SSD externe)
#    E:\VMware\VMs  (HDD data)

# Keep VMs running after Workstation closes:
# [[OK]] Activé: VMs continuent background
# [ ] Désactivé: Arrête VMs à fermeture Workstation

# Check for product updates:
# [ ] At startup (décocher si offline)
# [[OK]] Every 7 days


# ONGLET "INPUT":
# ═════════════

# Grab keyboard and mouse input on mouse click:
# [[OK]] Activé: Clic dans VM capture souris/clavier
# 
# Ungrab when Ctrl+Alt is pressed:
# [[OK]] Activé: Ctrl+Alt libère souris

# Optimize mouse for games:
# [[OK]] Activé si vous jouez dans VM (rare)


# ONGLET "HOT KEYS":
# ═════════════════

# Personnaliser raccourcis:
# 
# Ctrl+Alt: Release cursor (libérer souris)
# Ctrl+Alt+Enter: Full screen (plein écran)
# Ctrl+Alt+Insert: Send Ctrl+Alt+Del
# Ctrl+D: Snapshot

# Modifier si conflit avec OS hôte


# ONGLET "DISPLAY":
# ════════════════

# Autosize: Scale guest display
# [[OK]] Stretch guest (étirer pour remplir fenêtre)
# [ ] Keep aspect ratio (garder proportions)
# [ ] Autofit window (ajuster fenêtre à résolution guest)
# [ ] Autofit guest (ajuster guest à fenêtre)

# [RAPIDE] RECOMMANDATION:
# "Autofit guest" + VMware Tools installé = meilleure expérience


# ONGLET "USB":
# ════════════

# Default USB connection behavior:
# 
# • Ask me what to do
# • Connect to host (hôte)
# • Connect to foreground VM (VM active)
# 
# -> Choisir "Ask me" (contrôle manuel)

# Show notification when mouse connects to VM:
# [[OK]] Pratique pour savoir où est souris


# ONGLET "MEMORY":
# ═══════════════

# [ATTENTION] CRITIQUE POUR PERFORMANCE!

# Reserved memory:
# • Fit all virtual machine memory into reserved host RAM
# [========================================] 75%
# 
# Slider: Pourcentage RAM hôte réservé VMs
# 
# Exemple (32GB hôte):
# • 25%: 8GB VMs max, 24GB hôte conserve
# • 50%: 16GB VMs max, 16GB hôte conserve  <- Recommandé
# • 75%: 24GB VMs max, 8GB hôte conserve   <- Risqué!
# • 100%: 32GB VMs max, swapping probable!

# RÈGLE D'OR:
# Laisser minimum 8GB pour OS hôte
# 
# 16GB total -> Max 8GB VMs (50%)
# 32GB total -> Max 20GB VMs (65%)
# 64GB total -> Max 48GB VMs (75%)


# ONGLET "PRIORITY":
# ═════════════════

# VM execution priority:
# 
# • Take snapshots in background (recommandé)
#   -> Snapshot n'interrompt pas VM
# 
# • Background VMs have lower priority
#   -> VM non-active utilise moins CPU

# Input grabbed:
# • Normal: Priorité égale
# • High: VM active prioritaire (lag OS hôte possible)


# ONGLET "DEVICES":
# ════════════════

# Enable all devices for this virtual machine:
# [[OK]] CD/DVD drives
# [[OK]] Network adapters
# [[OK]] USB controllers
# 
# Décocher pour désactiver globalement


# ONGLET "SHARED VMS":
# ═══════════════════

# Server port: 443 (HTTPS)
# Enable sharing (partager VMs avec autres users)


# ONGLET "UPDATES":
# ════════════════

# Download all components:
# [[OK]] VMware Tools for Windows
# [[OK]] VMware Tools for Linux
# 
# Update installation folder:
# C:\Program Files (x86)\VMware\VMware Workstation


# SAUVEGARDER PRÉFÉRENCES:
# ═══════════════════════

# Toutes préférences dans:
# Windows: %APPDATA%\VMware\preferences.ini
# Linux: ~/.vmware/preferences


# ═══════════════════════════════════════════════════════════════════
# PARTIE 3: CRÉER PREMIÈRE MACHINE VIRTUELLE
# ═══════════════════════════════════════════════════════════════════


# ═══ 3.1 OBTENIR ISO SYSTÈME D'EXPLOITATION ═══

# QU'EST-CE QU'UN ISO?
# ═══════════════════

# ISO = Image disque (copie exacte CD/DVD)
# Format standard pour distribuer OS
# Extension: .iso

# ANALOGIE:
# ISO = Photo d'un DVD d'installation
# Vous "insérez" ce fichier dans lecteur DVD virtuel VM


# TÉLÉCHARGER UBUNTU SERVER (Recommandé débutants)
# ════════════════════════════════════════════════

# POURQUOI Ubuntu Server?
# • Gratuit et open-source
# • Documentation excellente
# • Communauté énorme
# • Stable (LTS = 5 ans support)
# • Idéal apprentissage Linux/Admin
# • Léger (pas d'interface graphique)

# URL OFFICIELLE:
# https://ubuntu.com/download/server

# VERSION LTS (Long Term Support):
# • Ubuntu Server 22.04.3 LTS (jusqu'à 2027)
# • Ubuntu Server 24.04 LTS (jusqu'à 2029)
# 
# Fichier téléchargé:
# ubuntu-24.04-live-server-amd64.iso
# Taille: ~2.5GB

# VERSION DESKTOP (Interface graphique):
# Si vous préférez GUI (débutants):
# ubuntu-24.04-desktop-amd64.iso
# Taille: ~5GB


# AUTRES OS POPULAIRES (Alternatives):
# ═══════════════════════════════════

# DEBIAN (Très stable, serveur)
# ─────────────────────────────
# URL: https://www.debian.org/distrib/netinst
# Fichier: debian-12.5.0-amd64-netinst.iso
# Taille: ~650MB
# Difficulté: Moyenne (moins user-friendly)

# CENTOS STREAM 9 (Enterprise, RedHat-based)
# ──────────────────────────────────────────
# URL: https://www.centos.org/download/
# Fichier: CentOS-Stream-9-latest-x86_64-dvd1.iso
# Taille: ~10GB
# Difficulté: Moyenne-Haute

# ROCKY LINUX / ALMALINUX (Alternative CentOS)
# ────────────────────────────────────────────
# URL: https://rockylinux.org/download
# Fichier: Rocky-9.3-x86_64-minimal.iso
# Taille: ~2GB
# Difficulté: Moyenne

# WINDOWS SERVER 2022 (Microsoft)
# ───────────────────────────────
# URL: https://www.microsoft.com/evalcenter
# Fichier: Windows_Server_2022_Eval.iso
# Taille: ~5GB
# Trial: 180 jours gratuit
# Difficulté: Basse (GUI familier)

# WINDOWS 11 (Desktop Microsoft)
# ─────────────────────────────
# URL: https://www.microsoft.com/software-download/windows11
# Fichier: Win11_23H2_English_x64.iso
# Taille: ~6GB
# Note: Nécessite TPM 2.0 (VM peut émuler)


# VÉRIFIER INTÉGRITÉ ISO (Important sécurité!)
# ════════════════════════════════════════════

# POURQUOI vérifier?
# • Téléchargement peut être corrompu
# • Éviter ISO modifié (malware)
# • Assurer installation propre

# MÉTHODE: Checksum SHA256

# LINUX:
# ─────
sha256sum ubuntu-24.04-live-server-amd64.iso

# Résultat:
# 45f873de9f8cb637345d6e66a583762730bbea30277ef7b32c9c3bd6700a32d2

# Comparer avec hash officiel site Ubuntu:
# Si identique [OK] Bon
# Si différent [X] Re-télécharger!


# WINDOWS:
# ───────
certutil -hashfile ubuntu-24.04-live-server-amd64.iso SHA256

# Résultat:
# SHA256 hash:
# 45f873de9f8cb637345d6e66a583762730bbea30277ef7b32c9c3bd6700a32d2


# ═══ 3.2 CRÉER VM AVEC WIZARD (ASSISTANT) ═══

# LANCER WIZARD:
# ═════════════

# Workstation -> File -> New Virtual Machine (Ctrl+N)
# Ou cliquer icône [+] dans toolbar


# ÉCRAN 1: WELCOME (Type de configuration)
# ════════════════════════════════════════

# ┌─────────────────────────────────────────┐
# │ New Virtual Machine Wizard             │
# ├─────────────────────────────────────────┤
# │                                         │
# │ What type of configuration?             │
# │                                         │
# │ [NOIR] Typical (Recommended)                │
# │    Quick setup with common settings    │
# │                                         │
# │ [BLANC] Custom (Advanced)                    │
# │    Full control over settings          │
# │                                         │
# │             [Next >]  [Cancel]         │
# └─────────────────────────────────────────┘

# TYPICAL (Recommandé débutants):
# • Configuration auto optimisée
# • Questions minimales
# • Rapide (5 minutes)

# CUSTOM (Avancé):
# • Contrôle total hardware
# • Choisir version hardware VM
# • Configurer chaque détail
# 
# -> Choisir CUSTOM pour ce guide (apprentissage)

# Clic "Custom" puis Next


# ÉCRAN 2: HARDWARE COMPATIBILITY
# ═══════════════════════════════

# ┌─────────────────────────────────────────┐
# │ Virtual Machine Hardware Compatibility  │
# ├─────────────────────────────────────────┤
# │                                         │
# │ Hardware compatibility:                 │
# │ [Workstation 17.x [BLACK_DOWN-POINTING_TRIANGLE]]                    │
# │                                         │
# │ Features available:                     │
# │ • Up to 128 vCPUs                       │
# │ • Up to 2TB RAM                         │
# │ • USB 3.2 support                       │
# │ • vTPM 2.0 support                      │
# │ • Secure Boot support                   │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# VERSIONS HARDWARE:
# • Workstation 17.x (Virtual Hardware 21) <- Dernier
# • Workstation 16.x (Virtual Hardware 19)
# • Workstation 15.x (Virtual Hardware 18)
# • Workstation 12.x (Virtual Hardware 12)
# • ESXi 8.0 (Virtual Hardware 20)
# • ESXi 7.0 (Virtual Hardware 19)

# QUAND choisir version ancienne?
# -> Migration vers ESXi ancien
# -> Compatibilité avec Workstation ancien

# RECOMMANDATION:
# Toujours choisir dernière version (17.x)
# -> Meilleures performances et features

# Next


# ÉCRAN 3: GUEST OPERATING SYSTEM
# ═══════════════════════════════

# ┌─────────────────────────────────────────┐
# │ Guest Operating System Installation     │
# ├─────────────────────────────────────────┤
# │                                         │
# │ Install from:                           │
# │                                         │
# │ [NOIR] Installer disc image file (iso):     │
# │    [Browse...]                          │
# │    C:\ISOs\ubuntu-24.04-server.iso      │
# │                                         │
# │ [BLANC] Installer disc:                      │
# │    Physical DVD drive                   │
# │                                         │
# │ [BLANC] I will install OS later              │
# │    (Create blank VM)                    │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# OPTIONS:

# 1. Installer disc image file (ISO) - RECOMMANDÉ
#    ────────────────────────────────────────────
#    • Pointer vers fichier .iso téléchargé
#    • Plus rapide que DVD physique
#    • Peut déconnecter après install
#    
#    Cliquer [Browse...] -> Sélectionner:
#    ubuntu-24.04-live-server-amd64.iso

# 2. Installer disc (DVD physique)
#    ─────────────────────────────
#    • Si DVD installation physique dans lecteur
#    • Rare aujourd'hui
#    • Plus lent que ISO

# 3. I will install OS later
#    ──────────────────────
#    • Crée VM vide (pas d'OS)
#    • Vous attachez ISO manuellement après
#    • Utile si ISO pas encore téléchargé

# EASY INSTALL (Ubuntu détecté):
# ─────────────────────────────
# Si ISO Ubuntu/Windows détecté, Workstation propose:
# 
# ┌─────────────────────────────────────────┐
# │ Easy Install detected!                  │
# │                                         │
# │ Full Name: [John Doe]                   │
# │ Username:  [john]                       │
# │ Password:  [********]                   │
# │                                         │
# │ VMware will install Ubuntu automatically│
# └─────────────────────────────────────────┘
# 
# -> Pratique mais DÉCOCHER "Easy Install" pour apprendre!
# -> On fera installation manuelle (éducatif)

# Next


# ÉCRAN 4: SELECT GUEST OS TYPE
# ═════════════════════════════

# ┌─────────────────────────────────────────┐
# │ Select a Guest Operating System         │
# ├─────────────────────────────────────────┤
# │                                         │
# │ Guest operating system:                 │
# │                                         │
# │ [NOIR] Linux                                 │
# │ [BLANC] Microsoft Windows                    │
# │ [BLANC] Other                                 │
# │                                         │
# │ Version: [Ubuntu 64-bit [BLACK_DOWN-POINTING_TRIANGLE]]             │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# CATÉGORIES:

# LINUX:
# • Ubuntu 64-bit (notre choix)
# • Debian 12.x 64-bit
# • Red Hat Enterprise Linux 9 64-bit
# • CentOS 9 64-bit
# • Fedora 64-bit
# • SUSE Linux Enterprise 15 64-bit
# • Oracle Linux 9 64-bit
# • Other Linux 5.x or later kernel 64-bit

# WINDOWS:
# • Windows 11 x64
# • Windows Server 2022
# • Windows 10 x64
# • Windows Server 2019
# • Windows 8.1 x64
# • Windows Server 2016

# OTHER:
# • FreeBSD 64-bit
# • Solaris 11 64-bit
# • Generic 64-bit
# 
# -> Sélectionner "Linux" + "Ubuntu 64-bit"

# Next


# ÉCRAN 5: NAME AND LOCATION
# ══════════════════════════

# ┌─────────────────────────────────────────┐
# │ Name the Virtual Machine                │
# ├─────────────────────────────────────────┤
# │                                         │
# │ Virtual machine name:                   │
# │ [Ubuntu Server 24.04]                   │
# │                                         │
# │ Location:                               │
# │ [C:\VMs\Ubuntu-Server-24.04]  [Browse..]│
# │                                         │
# │ Space required: ~40GB                   │
# │ Space available: 250GB                  │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# NOM VM:
# • Descriptif et clair
# • Éviter espaces/caractères spéciaux (mais possible)
# 
# [OK] BON:
# Ubuntu-Server-24.04
# Ubuntu-Web-Server
# CentOS-Database-01
# Win11-Desktop-Test
# 
# [X] ÉVITER:
# VM1 (pas descriptif)
# Test (trop générique)
# My VM!!! (caractères spéciaux)

# LOCATION (Emplacement disque):
# • Par défaut: C:\Users\VotreNom\Documents\Virtual Machines
# • Changer si:
#   - Disque C: plein
#   - SSD externe plus rapide
#   - Organisation personnelle
# 
# Exemples:
# D:\VMs\Ubuntu-Server-24.04
# E:\VMware\Production\Web-Server-01
# 
# Structure recommandée:
# D:\VMs\
# ├── Production\
# │   ├── Web-Server-01\
# │   └── Database-Server\
# ├── Development\
# │   └── Ubuntu-Dev\
# └── Testing\
#     └── Test-VM

# Next


# ÉCRAN 6: PROCESSOR CONFIGURATION
# ════════════════════════════════

# ┌─────────────────────────────────────────┐
# │ Processor Configuration                 │
# ├─────────────────────────────────────────┤
# │                                         │
# │ Number of processors: [1 [BLACK_DOWN-POINTING_TRIANGLE]]            │
# │                                         │
# │ Number of cores per processor: [2 [BLACK_DOWN-POINTING_TRIANGLE]]   │
# │                                         │
# │ Total processor cores: 2                │
# │                                         │
# │ Recommended: 2 cores                    │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# CONCEPTS:

# PROCESSORS (Sockets):
# • Nombre de CPU physiques (en VM = virtuel)
# • Généralement: 1 (sauf serveur multi-socket)

# CORES PER PROCESSOR:
# • Nombre de cores par CPU
# • Total vCPUs = Processors × Cores

# Exemples:
# • 1 processor × 2 cores = 2 vCPUs <- Serveur léger
# • 1 processor × 4 cores = 4 vCPUs <- Serveur moyen
# • 2 processors × 4 cores = 8 vCPUs <- Serveur lourd

# RECOMMANDATIONS:

# Ubuntu Server léger (Web, DNS, etc.):
# • 1 processor, 2 cores = 2 vCPUs [OK]

# Ubuntu Server moyen (App, Base données petite):
# • 1 processor, 4 cores = 4 vCPUs [OK]

# Ubuntu Server lourd (Database, Compilation):
# • 1 processor, 8 cores = 8 vCPUs [OK]

# RÈGLES:
# • Ne pas allouer plus de cores que hôte physique!
# • Ratio 1:1 idéal (1 vCPU = 1 core physique)
# • Maximum 4:1 acceptable (4 vCPUs = 1 core physique)
# 
# Exemple hôte 8 cores:
# [OK] VM1: 2 vCPUs, VM2: 2 vCPUs, VM3: 2 vCPUs = 6/8 utilisés
# [X] VM1: 8 vCPUs, VM2: 8 vCPUs = 16 vCPUs sur 8 physiques! (sur-allocation)

# Pour ce guide: Choisir 2 cores

# Next


# ÉCRAN 7: MEMORY CONFIGURATION
# ═════════════════════════════

# ┌─────────────────────────────────────────┐
# │ Memory for the Virtual Machine          │
# ├─────────────────────────────────────────┤
# │                                         │
# │ Memory for this VM:  [2048] MB          │
# │                                         │
# │ [====|-----------------------] 2GB/32GB │
# │  Min  Recommended    Max                │
# │  512MB   2048MB      16384MB            │
# │                                         │
# │ Guest OS maximum: 2TB                   │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# RECOMMANDATIONS:

# Ubuntu Server MINIMAL (CLI seulement):
# • 512MB: Fonctionne mais lent
# • 1024MB (1GB): Confortable minimum
# • 2048MB (2GB): Recommandé [OK]
# • 4096MB (4GB): Optimal

# Ubuntu Desktop (Interface graphique):
# • 2048MB: Minimum absolu
# • 4096MB (4GB): Recommandé [OK]
# • 8192MB (8GB): Confortable

# Windows Server:
# • 2048MB: Minimum Microsoft
# • 4096MB (4GB): Recommandé [OK]
# • 8192MB (8GB): Optimal

# Base de données (MySQL, PostgreSQL):
# • 4096MB (4GB): Petit
# • 8192MB (8GB): Moyen [OK]
# • 16384MB (16GB): Large

# RÈGLES:
# • Total RAM VMs < RAM physique hôte
# • Laisser minimum 4-8GB pour OS hôte
# 
# Exemples (32GB hôte):
# • Scénario 1: VM1 (8GB) + VM2 (8GB) + VM3 (4GB) + Hôte (8GB) = 28GB [OK]
# • Scénario 2: VM1 (16GB) + VM2 (16GB) + Hôte (4GB) = 36GB [X] (sur-allocation!)

# Pour ce guide: 2048MB (2GB)

# Next


# ÉCRAN 8: NETWORK TYPE
# ═════════════════════

# ┌─────────────────────────────────────────┐
# │ Network Type                            │
# ├─────────────────────────────────────────┤
# │                                         │
# │ [NOIR] Use network address translation (NAT)│
# │    VM accesses external network via host│
# │                                         │
# │ [BLANC] Use bridged networking               │
# │    VM appears as separate PC on network│
# │                                         │
# │ [BLANC] Use host-only networking             │
# │    VM isolated, host-only communication│
# │                                         │
# │ [BLANC] Do not use a network connection      │
# │    No network adapter                   │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# TYPES RÉSEAU (Détail complet Partie 6):

# NAT (Network Address Translation) - RECOMMANDÉ DÉBUTANTS
# ────────────────────────────────────────────────────────
# 
# [Internet] <--> [Hôte: 192.168.1.100]
#                    v NAT
#               [VM: 192.168.88.128]
# 
# FONCTIONNEMENT:
# • VM a IP privée (192.168.88.x)
# • Hôte fait NAT (masquerade)
# • VM accède Internet via hôte
# • VM invisible depuis réseau externe
# 
# AVANTAGES:
# [OK] Simple configuration (auto)
# [OK] VM accède Internet
# [OK] VM isolée (sécurité)
# [OK] Pas de conflit IP réseau
# 
# INCONVÉNIENTS:
# [X] VM pas accessible depuis autres PCs réseau
# [X] Nécessite port forwarding pour services
# 
# USAGE:
# • Débutants (défaut)
# • VM isolée test/dev
# • Accès Internet uniquement

# BRIDGED (Pont réseau)
# ─────────────────────
# 
# [Internet] <--> [Réseau LAN]
#                  v     v
#              [Hôte]  [VM]
#            192.168.1.100  192.168.1.150
# 
# FONCTIONNEMENT:
# • VM a IP sur MÊME réseau que hôte
# • VM = PC physique séparé (du point de vue réseau)
# • Routeur DHCP donne IP à VM
# 
# AVANTAGES:
# [OK] VM accessible depuis tout le réseau
# [OK] Pas de NAT (performance)
# [OK] Services VM utilisables (web server, SSH)
# 
# INCONVÉNIENTS:
# [X] Configuration plus complexe
# [X] Consomme IP réseau
# [X] VM exposée réseau (sécurité)
# 
# USAGE:
# • Serveur accessible (web, database)
# • Tests réseau réalistes
# • Environnement production-like

# HOST-ONLY (Hôte uniquement)
# ───────────────────────────
# 
# [Hôte: 192.168.80.1] <--> [VM: 192.168.80.128]
#        (Isolés du réseau externe)
# 
# FONCTIONNEMENT:
# • Réseau virtuel isolé hôte<->VMs
# • Pas d'accès Internet
# • VMs communiquent entre elles
# 
# AVANTAGES:
# [OK] Isolation totale (sécurité tests)
# [OK] VMs se voient
# [OK] Hôte accède VMs
# 
# INCONVÉNIENTS:
# [X] Pas d'Internet
# [X] VMs invisibles réseau externe
# 
# USAGE:
# • Lab isolé (tests malware, attaques)
# • Cluster VMs local
# • Formation sans risque réseau

# DO NOT USE NETWORK
# ─────────────────
# • Pas de carte réseau
# • VM complètement isolée
# • Usage: Tests offline, sécurité maximale

# RECOMMANDATION DÉBUTANTS:
# -> Choisir NAT (simple, sécurisé, Internet fonctionne)

# Next


# ÉCRAN 9: I/O CONTROLLER TYPES
# ═════════════════════════════

# ┌─────────────────────────────────────────┐
# │ Select I/O Controller Types             │
# ├─────────────────────────────────────────┤
# │                                         │
# │ SCSI Controller:                        │
# │ [NOIR] LSI Logic SAS (Recommended)          │
# │ [BLANC] BusLogic                             │
# │ [BLANC] LSI Logic Parallel                   │
# │ [BLANC] VMware Paravirtual                   │
# │                                         │
# │ NVMe Controller:                        │
# │ [ ] Add NVMe controller                  │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# CONTRÔLEURS SCSI:

# LSI Logic SAS (Recommandé)
# ─────────────────────────
# • Modern, performant
# • Support natif Linux récent
# • Disques > 2TB
# -> Choisir par défaut [OK]

# BusLogic (Ancien)
# ────────────────
# • Compatibilité anciens OS
# • Performance inférieure
# • Limite 2TB
# -> Éviter sauf vieux OS

# LSI Logic Parallel
# ─────────────────
# • Bon compromis ancien/nouveau
# • Performance correcte

# VMware Paravirtual (PVSCSI)
# ──────────────────────────
# • Meilleure performance possible!
# • Nécessite VMware Tools installé
# • Usage: Database, I/O intensive
# -> Choisir si haute performance requise

# NVMe CONTROLLER:
# ───────────────
# • Émule SSD NVMe (ultra-rapide)
# • Support Linux kernel 4.4+, Windows Server 2016+
# • Performance maximale
# • Activer si:
#   - OS récent supporté
#   - SSD hôte NVMe
#   - Performance critique

# RECOMMANDATION:
# -> LSI Logic SAS (défaut)
# -> Cocher NVMe si OS récent + besoin perfs

# Next


# ÉCRAN 10: SELECT DISK TYPE
# ══════════════════════════

# ┌─────────────────────────────────────────┐
# │ Select a Disk Type                      │
# ├─────────────────────────────────────────┤
# │                                         │
# │ [NOIR] NVMe (Recommended)                    │
# │    Modern, high performance             │
# │                                         │
# │ [BLANC] SCSI                                  │
# │    Traditional, compatible              │
# │                                         │
# │ [BLANC] SATA                                  │
# │    Standard consumer drives             │
# │                                         │
# │ [BLANC] IDE                                   │
# │    Legacy, old OS only                  │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# TYPES DISQUES:

# NVMe (Recommandé moderne)
# ────────────────────────
# • Émule SSD NVMe
# • Performance excellente
# • Support OS récent
# -> Choisir si OS supporte [OK]

# SCSI
# ────
# • Standard serveur
# • Bon compromis perfs/compatibilité
# • Fonctionne tous OS
# -> Choix sûr universel [OK]

# SATA
# ────
# • Émule disque SATA consumer
# • Performance moyenne
# • Compatibilité élevée
# -> OK pour desktop

# IDE (Ancien)
# ───────────
# • Technologie obsolète
# • Performance faible
# • Seulement vieux OS (Windows 98, etc.)
# -> Éviter!

# RECOMMANDATION:
# Ubuntu 24.04 -> NVMe ou SCSI
# Windows 11 -> NVMe
# CentOS 7 -> SCSI

# Pour ce guide: NVMe ou SCSI

# Next


# ÉCRAN 11: SELECT DISK
# ═════════════════════

# ┌─────────────────────────────────────────┐
# │ Select a Disk                           │
# ├─────────────────────────────────────────┤
# │                                         │
# │ [NOIR] Create a new virtual disk            │
# │    Create fresh disk for VM             │
# │                                         │
# │ [BLANC] Use an existing virtual disk         │
# │    Reuse .vmdk from another VM          │
# │                                         │
# │ [BLANC] Use a physical disk (advanced)       │
# │    Direct access to physical disk       │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# OPTIONS:

# CREATE NEW VIRTUAL DISK (Standard)
# ─────────────────────────────────
# • Créer fichier .vmdk neuf
# • Usage normal (99% cas)
# -> Choisir ceci [OK]

# USE EXISTING VIRTUAL DISK
# ────────────────────────
# • Pointer vers .vmdk existant
# • Usage:
#   - Réutiliser disque autre VM
#   - Migrer VM
#   - Partager disque entre VMs (attention!)
# 
# Exemple:
# D:\VMs\Old-Ubuntu\ubuntu.vmdk

# USE PHYSICAL DISK (Avancé/Dangereux!)
# ────────────────────────────────────
# • Accès DIRECT disque physique hôte
# • VM lit/écrit vraie partition (ex: /dev/sda2)
# • [ATTENTION] RISQUES:
#   - Corruption données hôte
#   - Perte données si erreur
#   - Complexe configuration
# • Usage rare:
#   - Dual-boot VM/Physical
#   - Tests hardware spécifiques
# 
# -> NE PAS UTILISER sauf expert!

# Pour ce guide: "Create a new virtual disk"

# Next


# ÉCRAN 12: SPECIFY DISK CAPACITY
# ═══════════════════════════════

# ┌─────────────────────────────────────────┐
# │ Specify Disk Capacity                   │
# ├─────────────────────────────────────────┤
# │                                         │
# │ Maximum disk size (GB): [20]            │
# │                                         │
# │ Recommended size: 20GB                  │
# │                                         │
# │ [NOIR] Allocate all disk space now          │
# │    Better performance, takes disk space│
# │                                         │
# │ [BLANC] Store virtual disk as single file    │
# │    Easier to move VM                    │
# │                                         │
# │ [BLANC] Split virtual disk into multiple files│
# │    Better for FAT32 filesystems         │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# TAILLE DISQUE:

# RECOMMANDATIONS PAR OS:

# Ubuntu Server minimal:
# • 10GB: Très serré (OS seulement)
# • 20GB: Minimum recommandé [OK]
# • 40GB: Confortable (apps + data)
# • 100GB: Large (databases, logs)

# Ubuntu Desktop:
# • 25GB: Minimum absolu
# • 40GB: Recommandé [OK]
# • 60GB: Confortable

# Windows Server 2022:
# • 32GB: Minimum Microsoft
# • 60GB: Recommandé [OK]
# • 100GB: Confortable

# Windows 11 Desktop:
# • 64GB: Minimum Microsoft
# • 100GB: Recommandé [OK]

# CentOS/Rocky Linux:
# • 10GB: Minimal install
# • 20GB: Recommandé [OK]
# • 40GB: Confortable

# ALLOCATION DISQUE:

# THIN PROVISIONING (Dynamic Growth)
# ─────────────────────────────────
# • Disque grandit dynamiquement
# • Fichier .vmdk commence petit
# • Exemple:
#   - Taille max: 20GB
#   - Ubuntu installé: 5GB utilisés
#   - Fichier .vmdk: ~5GB sur hôte [OK]
#   - VM remplit -> .vmdk grandit jusqu'à 20GB
# 
# AVANTAGES:
# [OK] Économie espace disque hôte
# [OK] Plusieurs VMs possible (thin)
# [OK] Snapshots plus petits
# 
# INCONVÉNIENTS:
# [X] Performance légèrement inférieure
# [X] Fragmentation possible
# [X] Sur-allocation risque (disque hôte plein!)
# 
# USAGE:
# • Labs, tests, dev
# • Multiples VMs simultanées
# • Espace disque hôte limité
# 
# -> DÉCOCHER "Allocate all disk space now"

# THICK PROVISIONING (Eager Zeroed)
# ────────────────────────────────
# • Disque alloué complet IMMÉDIATEMENT
# • Fichier .vmdk = taille max dès le début
# • Exemple:
#   - Taille max: 20GB
#   - Fichier .vmdk: 20GB sur hôte [OK]
#   - Même si VM utilise 5GB seulement
# 
# AVANTAGES:
# [OK] Performance maximale (pas de resize)
# [OK] Pas de fragmentation
# [OK] Prévisibilité espace disque
# 
# INCONVÉNIENTS:
# [X] Consomme espace immédiatement
# [X] Création VM plus lente (zéro-out)
# 
# USAGE:
# • Production (performance)
# • I/O intensif (databases)
# • Environnements critiques
# 
# -> COCHER "Allocate all disk space now"

# SINGLE FILE vs SPLIT FILES:

# SINGLE FILE (Recommandé)
# ───────────────────────
# • 1 fichier .vmdk unique
# • Exemple: ubuntu.vmdk (20GB)
# 
# AVANTAGES:
# [OK] Simple
# [OK] Meilleure performance (légèrement)
# [OK] Facile backup (1 fichier)
# 
# INCONVÉNIENTS:
# [X] Problème si filesystem limite taille fichier
# 
# -> Choisir par défaut

# SPLIT FILES (2GB chunks)
# ───────────────────────
# • Plusieurs fichiers 2GB
# • Exemple:
#   ubuntu-s001.vmdk (2GB)
#   ubuntu-s002.vmdk (2GB)
#   ubuntu-s003.vmdk (2GB)
#   ...
# 
# AVANTAGES:
# [OK] Compatible FAT32 (limite 4GB)
# [OK] Email possible (fichiers < 2GB)
# 
# INCONVÉNIENTS:
# [X] Nombreux fichiers (gestion)
# [X] Performance légèrement inférieure
# 
# USAGE:
# • Ancien filesystem (FAT32)
# • Transfert réseau lent
# • Email VMs
# 
# -> Éviter si pas de contrainte

# RECOMMANDATION CE GUIDE:
# • Taille: 20GB
# • Thin provisioned (décocher allocate)
# • Single file (cocher)

# Next


# ÉCRAN 13: SPECIFY DISK FILE
# ═══════════════════════════

# ┌─────────────────────────────────────────┐
# │ Specify Disk File                       │
# ├─────────────────────────────────────────┤
# │                                         │
# │ Disk file name:                         │
# │ [Ubuntu Server 24.04.vmdk]              │
# │                                         │
# │ Full path:                              │
# │ C:\VMs\Ubuntu-Server-24.04\             │
# │ Ubuntu Server 24.04.vmdk                │
# │                                         │
# │             [< Back]  [Next >]         │
# └─────────────────────────────────────────┘

# NOM FICHIER DISQUE:
# • Par défaut: Même que nom VM
# • Extension: .vmdk (Virtual Machine Disk)
# • Accepter défaut généralement [OK]

# FICHIERS CRÉÉS:
# ubuntu-server-24.04.vmdk (descriptor, <1KB)
# ubuntu-server-24.04-flat.vmdk (données, 20GB)
# 
# descriptor = Métadata (config disque)
# -flat = Données réelles

# Next


# ÉCRAN 14: READY TO CREATE
# ═════════════════════════

# ┌─────────────────────────────────────────┐
# │ Ready to Create Virtual Machine         │
# ├─────────────────────────────────────────┤
# │                                         │
# │ Summary:                                │
# │                                         │
# │ Name: Ubuntu Server 24.04               │
# │ Location: C:\VMs\Ubuntu-Server-24.04    │
# │ Hardware:                               │
# │   • Processors: 1 (2 cores)             │
# │   • Memory: 2048MB                      │
# │   • Disk: 20GB (thin)                   │
# │   • Network: NAT                        │
# │   • CD/DVD: ubuntu-24.04.iso            │
# │                                         │
# │ [ ] Power on after creation               │
# │ [x] Customize Hardware...                 │
# │                                         │
# │             [< Back]  [Finish]         │
# └─────────────────────────────────────────┘

# VÉRIFIER RÉSUMÉ:
# • Tout correct?
# • Specs conformes à besoin?

# OPTIONS:

# POWER ON AFTER CREATION:
# [ ] Décoché: VM créée mais éteinte
# [[OK]] Coché: VM démarre automatiquement après création

# CUSTOMIZE HARDWARE:
# [[OK]] Coché: Ouvre éditeur settings avant finir
#     -> Permet ajuster hardware
#     -> Ajouter périphériques
#     -> Modifier config
# 
# -> RECOMMANDÉ cocher pour vérifier/ajuster

# Cliquer [Finish]


# ÉDITEUR HARDWARE (Customize):
# ════════════════════════════

# Fenêtre "Virtual Machine Settings" s'ouvre

# ┌─────────────────────────────────────────────────────┐
# │ Virtual Machine Settings - Ubuntu Server 24.04      │
# ├──────────────────┬──────────────────────────────────┤
# │ Hardware | Options│                                  │
# ├──────────────────┤                                  │
# │                  │ Memory: 2048 MB                  │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] Memory         │ [======|----] 2GB/32GB           │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] Processors     │                                  │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] Hard Disk      │ Processors: 2                    │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] CD/DVD         │ [[OK]] Virtualization:              │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] Network        │     Intel VT-x/EPT               │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] USB            │                                  │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] Sound Card     │ Hard Disk (NVMe): 20GB           │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] Display        │ [NOIR] Thin provisioned               │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] Serial Port    │                                  │
# │ [BLACK_RIGHT-POINTING_TRIANGLE] Printer        │ CD/DVD (IDE):                    │
# │                  │ [NOIR] Use ISO: ubuntu-24.04.iso      │
# │ [Add...] [Remove]│ [x] Connected                      │
# │                  │ [x] Connect at power on            │
# │                  │                                  │
# │                  │ Network Adapter:                 │
# │                  │ [NOIR] NAT                            │
# │                  │                                  │
# │  [OK] [Cancel]   │                                  │
# └──────────────────┴──────────────────────────────────┘

# VÉRIFICATIONS:

# 1. MEMORY
#    • 2048MB minimum pour Ubuntu Server [OK]
#    • Ajuster si plus de RAM hôte disponible

# 2. PROCESSORS
#    • 2 cores = bon départ [OK]
#    • Vérifier "Virtualization engine" activé

# 3. HARD DISK
#    • 20GB adapté Ubuntu Server basique [OK]
#    • Type: NVMe ou SCSI

# 4. CD/DVD
#    • [NOIR] Use ISO image file
#    • [[OK]] Connected
#    • [[OK]] Connect at power on
#    • Pointe vers ubuntu-24.04.iso [OK]

# 5. NETWORK ADAPTER
#    • NAT sélectionné [OK]
#    • [[OK]] Connected

# 6. USB CONTROLLER
#    • USB 3.1 par défaut [OK]
#    • [[OK]] Show all USB input devices

# 7. SOUND CARD
#    • Auto detect généralement [OK]
#    • Peu important pour serveur (peut retirer)

# 8. DISPLAY
#    • Accelerate 3D graphics: [[OK]] si Desktop, [ ] si Server
#    • Graphics memory: 128MB suffit serveur

# AJOUTER PÉRIPHÉRIQUE:
# Cliquer [Add...] -> Choisir type:
# • Hard Disk (disque additionnel)
# • Network Adapter (carte réseau additionnelle)
# • Floppy (ancien, inutile aujourd'hui)
# • CD/DVD (lecteur additionnel)
# • Serial Port (debug kernel)
# • Parallel Port (imprimante, ancien)
# • Generic SCSI Device (spécial)
# • etc.

# RETIRER PÉRIPHÉRIQUE:
# Sélectionner dans liste -> [Remove]
# Exemple: Retirer Sound Card si serveur CLI

# Cliquer [OK] pour fermer


# FICHIERS VM CRÉÉS:
# ═════════════════

# Dossier: C:\VMs\Ubuntu-Server-24.04\

# ├── Ubuntu Server 24.04.vmx          (Config VM)
# ├── Ubuntu Server 24.04.vmxf         (Info teams/sharing)
# ├── Ubuntu Server 24.04.vmdk         (Descriptor disque)
# ├── Ubuntu Server 24.04-flat.vmdk    (Données disque)
# ├── Ubuntu Server 24.04.nvram        (BIOS settings)
# └── vmware.log                        (Log démarrage)

# TAILLE TOTALE (avant install OS):
# • .vmx: ~3KB (texte)
# • .vmdk descriptor: ~500 bytes
# • -flat.vmdk: ~500MB (thin) ou 20GB (thick)
# • .nvram: ~128KB
# -> Total: ~500MB si thin, 20GB si thick


# VM PRÊTE! Prochaine étape: Installer OS

# [Continuer Partie 4 pour installation Ubuntu...]


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 3: CRÉATION PREMIÈRE MACHINE VIRTUELLE
# ═══════════════════════════════════════════════════════════════════

# RÉCAPITULATIF PARTIE 3:
# ──────────────────────
# [OK] Téléchargé ISO Ubuntu Server 24.04
# [OK] Vérifié checksum ISO (sécurité)
# [OK] Lancé wizard "New Virtual Machine"
# [OK] Choisi Custom (contrôle total)
# [OK] Sélectionné hardware compatibility (v21)
# [OK] Attaché ISO installation
# [OK] Configuré Guest OS (Ubuntu 64-bit)
# [OK] Nommé VM et choisi emplacement disque
# [OK] Alloué ressources:
#   - 2 vCPUs (1 processor, 2 cores)
#   - 2048MB RAM (2GB)
#   - 20GB disque NVMe/SCSI (thin provisioned)
#   - Réseau NAT
# [OK] Vérifié configuration dans Hardware Settings
# [OK] VM créée avec succès!

# PROCHAINE PARTIE:
# • Démarrer VM
# • Installer Ubuntu Server 24.04
# • Configuration réseau
# • Installer VMware Tools
# • Post-installation


# ═══════════════════════════════════════════════════════════════════
# À SUIVRE: PARTIE 4 - INSTALLER UBUNTU SERVER
# ═══════════════════════════════════════════════════════════════════

# [Le guide continue avec 15+ parties supplémentaires couvrant:
#  - Installation OS détaillée
#  - Configuration réseau avancée
#  - Snapshots et clonage
#  - VMware Tools
#  - Gestion multi-VMs
#  - ESXi hyperviseur
#  - vCenter Server
#  - Storage avancé
#  - High Availability
#  - Performance tuning
#  - Troubleshooting
#  - Best practices production]


# ═══════════════════════════════════════════════════════════════════
# PARTIE 4: INSTALLATION UBUNTU SERVER 24.04 LTS
# ═══════════════════════════════════════════════════════════════════

# Dans cette partie, on installe Ubuntu Server dans notre VM créée
# Processus complet du boot ISO jusqu'au système opérationnel


# ═══════════════════════════════════════════════════════════════════
# 4.1 - DÉMARRER LA MACHINE VIRTUELLE
# ═══════════════════════════════════════════════════════════════════

# POURQUOI démarrer la VM maintenant?
# • VM créée = blueprint vide (hardware virtuel défini)
# • Besoin d'installer OS pour avoir système fonctionnel
# • ISO déjà attaché au lecteur CD/DVD
# • VM va booter sur ISO -> lance l'installateur

# QUAND démarrer?
# • Immédiatement après création VM
# • Après avoir vérifié ISO correct dans CD/DVD
# • Quand ressources hôte disponibles (pas de surcharge)

# COMMENT démarrer:
# ────────────────

# MÉTHODE 1: Via Library (sidebar)
# 1. Dans VMware Workstation sidebar (Library)
# 2. Cliquer sur VM "Ubuntu Server 24.04"
# 3. Cliquer bouton vert [[BLACK_RIGHT-POINTING_TRIANGLE] Power on this virtual machine]

# MÉTHODE 2: Via menu
# Menu [VM] -> [Power] -> [Power On]

# MÉTHODE 3: Via raccourci
# Ctrl + B (Power On/Off toggle)


# CE QUI SE PASSE AU DÉMARRAGE:
# ═════════════════════════════

# PHASE 1: BIOS virtuel
# • VM lit .nvram (BIOS settings)
# • Affiche splash screen VMware
# • Check boot order:
#   1. CD-ROM (ISO attaché) <- priorité
#   2. Hard Disk (vide pour l'instant)
#   3. Network (PXE boot)

# PHASE 2: Boot sur ISO
# • VM lit ubuntu-24.04-live-server-amd64.iso
# • Charge kernel Linux depuis ISO
# • Lance initramfs (ramdisk initial)
# • Démarre installateur Ubuntu Server (Subiquity)

# PHASE 3: Écran d'accueil
# • Apparition menu GRUB:
#   * Try or Install Ubuntu Server
#   * Ubuntu Server (safe graphics)
#   * Test memory
#   * Boot from next volume
#   * UEFI Firmware Settings
# • Sélection automatique après 30 secondes
# • Ou appuyer [Enter] pour "Try or Install Ubuntu Server"


# PREMIÈRE INTERACTION:
# ════════════════════

# Console VM:
# • Fenêtre noire avec texte blanc
# • Messages kernel Linux qui défilent:
#   [    0.000000] Linux version 6.8.0-31-generic
#   [    0.524288] PCI: Using configuration type 1
#   [    1.234567] vmw_vmci 0000:00:07.7: Found VMCI PCI device
#   [    2.456789] vmwgfx 0000:00:0f.0: enabling device
# • Ne pas paniquer: c'est normal!
# • Attendre 30-60 secondes

# ASTUCE INTERACTION:
# • Cliquer dans fenêtre VM pour "capturer" souris/clavier
# • Message apparaît: "Press Ctrl+Alt to release cursor"
# • Ctrl+Alt pour libérer curseur et revenir à Windows/Linux hôte


# ═══════════════════════════════════════════════════════════════════
# 4.2 - PROCESSUS D'INSTALLATION (SUBIQUITY)
# ═══════════════════════════════════════════════════════════════════

# POURQUOI cet installateur?
# • Subiquity = nouvel installateur Ubuntu Server (depuis 20.04)
# • Interface TUI (Text-based User Interface) moderne
# • Navigation clavier: Flèches, Tab, Enter, Espace
# • Processus guidé en 14 écrans
# • Automatisation possible via cloud-init (avancé)

# QUAND utiliser mode manuel vs automatique?
# • Manuel: Première installation, apprentissage, contrôle total
# • Automatique: Déploiement masse, cloud, CI/CD
# • On fait manuel pour comprendre!


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 1/14: CHOIX LANGUE
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Welcome! Please choose your preferred         │
# │  language.                                     │
# │                                                │
# │  > English                                     │
# │    Español                                     │
# │    Français                                    │
# │    Deutsch                                     │
# │    Italiano                                    │
# │    日本語                                       │
# │    简体中文                                     │
# │    ... (50+ langues)                           │
# │                                                │
# │         [Tab] to continue                      │
# └────────────────────────────────────────────────┘

# NAVIGATION:
# • Flèche ^/v: Changer sélection
# • Enter: Valider choix
# • Tab: Passer à bouton suivant

# RECOMMANDATION:
# • Choisir "English" (messages d'erreur Google-ables)
# • Ou votre langue si débutant absolu
# • Langue affecte: interface install, messages système, locales

# IMPACT:
# • Messages système en anglais -> plus de ressources en ligne
# • Français -> Facilité lecture mais docs anglophones majoritaires
# • Changeable post-installation via locales

# -> Sélectionner [English] -> [Enter]


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 2/14: MISE À JOUR INSTALLATEUR
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Installer update available                    │
# │                                                │
# │  The installer has an update available.        │
# │  The update includes bug fixes and new         │
# │  features.                                     │
# │                                                │
# │  Current version: 24.04                        │
# │  New version: 24.04.1                          │
# │                                                │
# │  [Update to the new installer]                 │
# │  [Continue without updating]                   │
# └────────────────────────────────────────────────┘

# POURQUOI cette option?
# • ISO peut avoir été créée il y a plusieurs mois
# • Ubuntu publie mises à jour installateur régulièrement
# • Corrections bugs, amélioration détection hardware, patches sécurité

# QUAND mettre à jour?
# • VM avec Internet via NAT [OK] -> Update recommandé
# • Réseau isolé/hors ligne -> Continue without updating
# • Production: Skip update (reproductibilité déploiements)
# • Lab/test: Update (dernières features)

# COMMENT décider:
# SI Internet disponible ET pas contrainte temps:
#   -> Update (5-10 minutes supplémentaires)
# SINON:
#   -> Continue (installateur de base suffisant pour 99% cas)

# PROCESSUS SI UPDATE:
# • Télécharge ~50-100MB
# • Décompresse nouvelle version
# • Redémarre installateur automatiquement
# • Reprend à écran langue

# -> Pour ce guide: [Continue without updating] -> [Enter]
# (plus rapide, fonctionnel identique pour usage basique)


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 3/14: CONFIGURATION CLAVIER
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Keyboard configuration                        │
# │                                                │
# │  Layout: [English (US)            [BLACK_DOWN-POINTING_TRIANGLE]]           │
# │                                                │
# │  Variant: [English (US)           [BLACK_DOWN-POINTING_TRIANGLE]]           │
# │                                                │
# │  ┌──────────────────────────────────────────┐ │
# │  │ Test keyboard layout:                    │ │
# │  │ [                              ]         │ │
# │  └──────────────────────────────────────────┘ │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI crucial?
# • Détermine mapping touches physiques <-> caractères
# • AZERTY (France) ≠ QWERTY (US) ≠ QWERTZ (Allemagne)
# • Erreur = frustration totale (ex: @ sur AZERTY = AltGr+à)
# • Symboles impactés: @, #, $, [, ], {, }, |, \, ~, etc.
# • Critique pour commandes shell et programmation!

# LAYOUT POPULAIRES:
# • English (US): QWERTY standard, touche Enter verticale
# • English (UK): £ au lieu de #, " et @ inversés
# • French: AZERTY, chiffres en Shift, M après L
# • German: QWERTZ, Y et Z inversés, ä ö ü
# • Spanish: QWERTY avec ñ, ¿, ¡

# COMMENT CHOISIR:
# 1. Identifier votre clavier physique:
#    • Regarder disposition touches (AZERTY vs QWERTY)
#    • Vérifier stickers touches spéciales
#    • Tester touches: ; : @ # [ ] { }

# 2. Sélectionner Layout:
#    • Tab pour aller à dropdown Layout
#    • Enter pour ouvrir menu
#    • Flèches pour naviguer
#    • Enter pour valider
#    Exemple France: French -> French (AZERTY)
#    Exemple US: English (US) -> English (US)

# 3. Choisir Variant (optional):
#    • AZERTY standard vs AZERTY Macintosh
#    • QWERTY US vs US International
#    • Généralement: garder premier choix

# 4. TESTER ABSOLUMENT:
#    • Tab vers "Test keyboard layout"
#    • Taper caractères spéciaux:
#      @ # $ [ ] { } | \ < > ~ ` ; : " ' / ? .
#    • Vérifier correspondance avec clavier physique
#    • Si caractère wrong: revenir Layout/Variant

# ERREUR COMMUNE:
# [X] Utilisateur AZERTY qui garde English (US)
# -> Plus tard lors connexion SSH:
#   Mot de passe MyP@ssw0rd! -> QyPàssw0rd! (échec login)
#   Commande cd /home -> cd :hoqe (erreur bash)

# ANALOGIE:
# Layout clavier = plan maison
# • Mauvais plan -> chercher interrupteur lumière dans le noir
# • Bon plan -> muscle memory fonctionnel

# RECOMMANDATION PRODUCTION:
# • English (US) si équipe internationale (standard de facto)
# • Layout local si équipe unique pays
# • Documenter choix dans runbook!

# -> Sélectionner votre layout -> [Tab] vers [Done] -> [Enter]


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 4/14: TYPE D'INSTALLATION
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Choose type of install                        │
# │                                                │
# │  ( ) Ubuntu Server (minimized)                 │
# │      • Minimal footprint                       │
# │      • No snapd, no LXD                        │
# │      • ~2GB disk usage                         │
# │                                                │
# │  (•) Ubuntu Server                             │
# │      • Standard server installation            │
# │      • Includes common tools                   │
# │      • ~5GB disk usage                         │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI 2 choix?
# • Minimized: Containers, microservices, edge computing
# • Standard: Serveurs traditionnels, VM polyvalentes

# DIFFÉRENCES DÉTAILLÉES:
# ═══════════════════════

# Ubuntu Server (Standard):
# • Packages: ~500 packages pré-installés
# • Outils: curl, wget, vim, git, ssh, python3
# • Snapd: Présent (système paquets Snap)
# • LXD: Inclus (gestion containers)
# • Cloud-init: Installé (provisionning cloud)
# • Size: ~5GB après install
# • Use case: 80% des installations

# Ubuntu Server (Minimized):
# • Packages: ~250 packages (strict nécessaire)
# • Outils: Kernel, systemd, apt, openssh-server, netplan
# • Snapd: Absent (économie espace/ressources)
# • LXD: Absent (installer manuellement si besoin)
# • Size: ~2GB après install
# • Use case: IoT, edge devices, containers base image

# TABLEAU COMPARAISON:
# ╔═══════════════════╦══════════╦══════════════╗
# ║ Feature           ║ Standard ║ Minimized    ║
# ╠═══════════════════╬══════════╬══════════════╣
# ║ Disk usage        ║ ~5GB     ║ ~2GB         ║
# ║ Memory base       ║ ~500MB   ║ ~300MB       ║
# ║ Packages count    ║ ~500     ║ ~250         ║
# ║ Boot time         ║ ~20s     ║ ~15s         ║
# ║ Snapd             ║ Yes      ║ No           ║
# ║ LXD containers    ║ Yes      ║ No           ║
# ║ Man pages         ║ Yes      ║ No           ║
# ║ Recommended for   ║ General  ║ Specialized  ║
# ╚═══════════════════╩══════════╩══════════════╝

# QUAND choisir Minimized?
# • Base pour Docker images (layer size critique)
# • Raspberry Pi / ARM devices (ressources limitées)
# • Appliances réseau (firewall, router)
# • Kubernetes nodes (kubelet seul nécessaire)
# • Déploiements mass scale (coût stockage)

# QUAND choisir Standard?
# • Apprentissage Linux (outils présents)
# • Serveur web/database traditionnel
# • Environnement développement
# • Première installation VMware
# • Quand espace disque non-critique

# ERREUR DÉBUTANT:
# [X] Choisir Minimized pour "optimiser"
# -> Plus tard: "Pourquoi vim n'existe pas?"
# -> Frustration car besoin installer manuellement tout

# ANALOGIE:
# Standard = Appartement meublé (prêt à habiter)
# Minimized = Appartement vide (apporter propres meubles)

# RECOMMANDATION GUIDE:
# • Standard pour apprentissage (plus de tools out-of-box)
# • Minimized une fois expérimenté (optimisation consciente)

# -> Sélectionner [Ubuntu Server] (standard) -> [Done] -> [Enter]


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 5/14: CONFIGURATION RÉSEAU
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Network connections                           │
# │                                                │
# │  ens33  ethernet  192.168.120.128/24           │
# │         DHCPv4    via 192.168.120.254          │
# │                                                │
# │  [Edit IPv4]  [Edit IPv6]  [Disable]           │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI cette étape?
# • VM a détecté carte réseau (ens33 dans notre cas)
# • Configuration automatique via DHCP NAT VMware
# • Peut configurer IP statique si besoin

# INTERFACE RÉSEAU DÉTECTÉE:
# ═════════════════════════

# Nom: ens33
# • ens = Ethernet Network System
# • 33 = Slot PCI où carte virtuelle attachée
# • Ancien nom: eth0 (deprecated depuis systemd 197)
# • Naming scheme: Predictable Network Interface Names

# POURQUOI ens33 et pas eth0?
# • Old style: eth0, eth1, eth2 (ordre détection variable)
# • New style: Basé sur slot hardware (prévisible)
# • VM Workstation: toujours ens33 (slot 33 fixe)
# • ESXi: Peut varier selon config hardware

# CONFIGURATION DHCP AFFICHÉE:
# ═══════════════════════════

# IP: 192.168.120.128/24
# • 192.168.120.0/24 = Subnet NAT VMware par défaut
# • 192.168.120.128 = IP allouée par DHCP VMware
# • /24 = Masque 255.255.255.255.0 (256 IPs possibles)

# Gateway: 192.168.120.2 (implicite)
# • VMware NAT gateway automatique
# • Route tout trafic externe vers hôte Windows/Linux

# DNS: 192.168.120.2 (implicite)
# • VMware DHCP fournit aussi DNS
# • Forward vers DNS hôte (Google 8.8.8.8, ISP, etc.)

# QUAND garder DHCP?
# • VM desktop/workstation (IP variable acceptable)
# • Lab/testing (recréation VMs fréquente)
# • Accès externe non requis
# • Simplicité prioritaire

# QUAND utiliser IP statique?
# • Serveur web (DNS point vers IP fixe)
# • Base de données (clients connaissent IP)
# • SSH régulier (pas de recherche IP)
# • Production (prévisibilité réseau)

# COMMENT CONFIGURER IP STATIQUE:
# ═══════════════════════════════

# [Edit IPv4] -> [Enter]
# ┌────────────────────────────────────────────────┐
# │  IPv4                                          │
# │                                                │
# │  IPv4 Method: ( ) Automatic (DHCP)             │
# │               (•) Manual                       │
# │               ( ) Disabled                     │
# │                                                │
# │  Subnet:    [192.168.120.0/24          ]       │
# │  Address:   [192.168.120.100           ]       │
# │  Gateway:   [192.168.120.2             ]       │
# │  Name servers: [192.168.120.2          ]       │
# │  Search domains: [                     ]       │
# │                                                │
# │            [Save]   [Cancel]                   │
# └────────────────────────────────────────────────┘

# VALEURS RECOMMANDÉES IP STATIQUE:
# • Subnet: 192.168.120.0/24 (garder subnet VMware)
# • Address: 192.168.120.100-253 (éviter 1-99 DHCP pool)
# • Gateway: 192.168.120.2 (gateway NAT VMware)
# • DNS: 192.168.120.2 ou 8.8.8.8,8.8.4.4 (Google)
# • Search domains: Laisser vide (non requis NAT)

# ERREURS COMMUNES:
# [X] Address hors subnet: 192.168.1.100 (wrong network!)
# [X] Gateway incorrect: 192.168.120.1 (n'existe pas)
# [X] Oublier DNS: Résolution noms impossible

# VÉRIFICATION RAPIDE:
# • Subnet & Address même réseau: 192.168.120.x
# • Gateway dans même subnet: 192.168.120.y
# • DNS accessible: Même subnet ou Internet (8.8.8.8)

# RECOMMANDATION DÉBUTANT:
# -> GARDER DHCP pour première install
# • Moins d'erreurs possibles
# • Changement possible post-installation
# • Focus sur reste installation

# -> [Done] -> [Enter] (accepter config DHCP actuelle)


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 6/14: CONFIGURATION PROXY
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Configure proxy                               │
# │                                                │
# │  If this system requires a proxy to connect    │
# │  to the internet, enter its details here.      │
# │                                                │
# │  Proxy address: [                          ]   │
# │                                                │
# │  Examples:                                     │
# │    http://proxy.example.com:3128               │
# │    http://user:pass@proxy.local:8080           │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI écran proxy?
# • Réseaux entreprise utilisent souvent proxies HTTP/HTTPS
# • Proxy = Intermédiaire entre client et Internet
# • Requis pour télécharger packages pendant installation

# QUAND utiliser proxy?
# • Réseau entreprise avec politique sécurité stricte
# • Connexion Internet filtrée/contrôlée
# • VM dans réseau isolé nécessitant gateway spécifique
# • Jamais pour home lab NAT standard

# FORMAT PROXY:
# http://[username:password@]proxy.host:port

# Exemples:
# • http://proxy.company.com:8080
# • http://10.0.0.1:3128
# • http://john:secret@proxy.local:8888

# TYPES PROXY COURANTS:
# • Squid: Open source, port 3128 par défaut
# • Microsoft TMG/ISA: Entreprise Windows, port 8080
# • Blue Coat: Enterprise-grade, port variable
# • Privoxy: Privacy-focused, port 8118

# IMPACT SI CONFIGURÉ:
# • apt: Télécharge packages via proxy
# • wget/curl: Route trafic via proxy
# • Environment vars: http_proxy, https_proxy, no_proxy
# • Fichiers affectés:
#   /etc/apt/apt.conf.d/01proxy
#   /etc/environment

# ERREUR COMMUNE:
# [X] Configurer proxy si pas requis
# -> Bloque téléchargements packages
# -> Installation échoue

# TEST SI PROXY REQUIS:
# Dans navigateur hôte Windows/Linux:
# • Settings -> Network -> Proxy
# • Si "No proxy" ou "Direct connection" -> Pas besoin
# • Si URL proxy visible -> Noter pour Ubuntu

# RECOMMANDATION HOME LAB:
# -> LAISSER VIDE (aucun proxy)
# • NAT VMware gère connexion Internet directement
# • Proxy complique debugging pour débutants

# -> [Done] -> [Enter] (champ vide)


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 7/14: MIROIR ARCHIVE UBUNTU
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Configure Ubuntu archive mirror               │
# │                                                │
# │  If you use an alternative mirror for Ubuntu,  │
# │  enter its details here.                       │
# │                                                │
# │  Mirror address:                               │
# │  [http://archive.ubuntu.com/ubuntu         ]   │
# │                                                │
# │  [ ] Use a separate security mirror            │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI changer miroir?
# • archive.ubuntu.com = Miroir officiel canonical (USA)
# • Distance géographique affecte vitesse téléchargement
# • Miroirs locaux -> Download plus rapide
# • Économie bande passante si miroir interne entreprise

# QUAND utiliser miroir alternatif?
# • Connexion lente vers archive.ubuntu.com
# • Entreprise avec miroir APT local (offline install)
# • Pays avec restrictions réseau
# • ISP avec cache Ubuntu local

# MIROIRS DISPONIBLES PAR PAYS:
# ═══════════════════════════════

# France:
# • http://fr.archive.ubuntu.com/ubuntu
# • http://ubuntu.univ-nantes.fr/ubuntu
# • http://ubuntu.mirrors.ovh.net/ubuntu

# Canada:
# • http://ca.archive.ubuntu.com/ubuntu
# • http://mirror.csclub.uwaterloo.ca/ubuntu

# Germany:
# • http://de.archive.ubuntu.com/ubuntu
# • http://ftp.halifax.rwth-aachen.de/ubuntu

# Global CDN (auto):
# • http://archive.ubuntu.com/ubuntu (GeoDNS, optimal)

# COMMENT TESTER MIROIR:
# Dans navigateur hôte:
# • http://fr.archive.ubuntu.com/ubuntu/dists/noble/
# • Si page charge -> Miroir fonctionnel
# • Check vitesse avec wget:
#   wget -O /dev/null http://miroir/file.deb

# SECURITY MIRROR:
# • Checkbox "Use separate security mirror"
# • Patches sécurité sur miroir dédié: security.ubuntu.com
# • Généralement laisser décoché (miroir principal inclut)

# FORMAT MIROIR:
# http://miroir.example.com/ubuntu
# • DOIT finir par /ubuntu
# • Pas de trailing slash final
# • HTTP ou HTTPS accepté

# FICHIER GÉNÉRÉ POST-INSTALL:
# /etc/apt/sources.list
# deb http://archive.ubuntu.com/ubuntu noble main restricted
# deb http://archive.ubuntu.com/ubuntu noble-updates main restricted
# deb http://security.ubuntu.com/ubuntu noble-security main restricted

# ERREUR COMMUNE:
# [X] Entrer miroir incorrect/non-fonctionnel
# -> Installation bloque à "Downloading packages"
# -> Nécessite redémarrage install

# VÉRIFICATION AVANT VALIDER:
# • URL accessible depuis VM? (test ping si pas sûr)
# • Miroir contient dépôts Ubuntu? (vérifier avec navigateur)

# RECOMMANDATION:
# -> GARDER DÉFAUT archive.ubuntu.com
# • GeoDNS redirige automatiquement vers serveur proche
# • Fiabilité maximale (Canonical infrastructure)
# • Changeable post-installation dans sources.list

# -> [Done] -> [Enter]


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 8/14: CONFIGURATION STOCKAGE (CRUCIAL!)
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Guided storage configuration                  │
# │                                                │
# │  ( ) Use an entire disk                        │
# │      [SCSI3 NVME VMware Virtual disk 20G]      │
# │      ├─ Set up this disk as an LVM group       │
# │      └─ Encrypt LVM with LUKS                  │
# │                                                │
# │  ( ) Custom storage layout                     │
# │      Manual partitioning for experts           │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI configuration stockage?
# • Définit comment 20GB disque virtuel sera utilisé
# • Partitions = Divisions logiques du disque
# • Filesystem = Système organisation fichiers sur partition
# • Décision affecte performance, flexibilité, sécurité

# OPTIONS DISPONIBLES:
# ═══════════════════

# 1. USE ENTIRE DISK (Recommandé débutants)
#    • Partitionnement automatique Ubuntu
#    • Layout: Boot + Root + Swap
#    • Simple, rapide, fonctionnel

# 2. USE ENTIRE DISK + LVM
#    • LVM = Logical Volume Manager
#    • Flexibilité redimensionnement partitions
#    • Snapshots filesystems possibles
#    • Complexité moyenne

# 3. USE ENTIRE DISK + LVM + LUKS
#    • LUKS = Linux Unified Key Setup (chiffrement)
#    • Disque entier chiffré
#    • Passphrase au boot requis
#    • Performance ~5-10% overhead

# 4. CUSTOM STORAGE LAYOUT
#    • Contrôle total partitionnement
#    • Multiple disques, RAID software
#    • Experts uniquement!


# COMPARAISON DÉTAILLÉE:
# ════════════════════

# STANDARD (Entire disk sans options):
# ╔════════════════╦══════════╦═══════════════════╗
# ║ Partition      ║ Size     ║ Mount             ║
# ╠════════════════╬══════════╬═══════════════════╣
# ║ /dev/sda1      ║ 1MB      ║ BIOS boot         ║
# ║ /dev/sda2      ║ 1.5GB    ║ /boot             ║
# ║ /dev/sda3      ║ ~18.5GB  ║ / (root)          ║
# ╚════════════════╩══════════╩═══════════════════╝
# Swap: File-based /swapfile (économie partition)

# LVM (Entire disk + LVM):
# ╔════════════════╦══════════╦═══════════════════╗
# ║ Volume         ║ Size     ║ Mount             ║
# ╠════════════════╬══════════╬═══════════════════╣
# ║ /dev/sda1      ║ 1MB      ║ BIOS boot         ║
# ║ /dev/sda2      ║ 1.5GB    ║ /boot             ║
# ║ /dev/sda3      ║ ~18.5GB  ║ LVM PV            ║
# ║  ├─vg-root     ║ ~17.5GB  ║ /                 ║
# ║  └─vg-swap     ║ 1GB      ║ swap              ║
# ╚════════════════╩══════════╩═══════════════════╝

# LVM + LUKS:
# • Identique LVM mais:
# • /dev/sda3 = LUKS container
# • Decrypt au boot -> Accès LVM volumes
# • Tout chiffré sauf /boot (kernel doit booter)


# QUAND UTILISER CHAQUE OPTION:
# ═════════════════════════════

# Standard (Entire disk):
# [OK] Première installation
# [OK] Lab/testing
# [OK] Performance maximale
# [OK] Simplicité prioritaire
# [X] Pas flexibilité redimensionnement
# [X] Pas snapshots

# LVM:
# [OK] Production servers
# [OK] Besoin resize partitions plus tard
# [OK] Snapshots filesystems (backup/restore)
# [OK] Multiple disques agrégés
# [X] Complexité légère
# [X] Overhead ~1-2%

# LVM + LUKS:
# [OK] Données sensibles (GDPR, HIPAA)
# [OK] Laptop/portable (risque vol)
# [OK] Multi-tenant environments
# [X] Passphrase boot requis (pas auto-start)
# [X] Performance -5-10%
# [X] Récupération données difficile si passphrase oubliée

# Custom:
# [OK] RAID software (mdadm)
# [OK] Multiple disques séparés (/home, /var, /opt)
# [OK] Optimisations spécifiques (SSD partitioning)
# [X] Expertise requise
# [X] Erreurs partitionnement = système instable


# DÉTAILS TECHNIQUES PARTITIONS:
# ══════════════════════════════

# /dev/sda1 (BIOS boot) - 1MB:
# • Requis pour boot BIOS legacy
# • GRUB stage 1.5 stocké ici
# • Ne PAS supprimer!

# /dev/sda2 (/boot) - 1.5GB:
# • Kernels Linux stockés ici
# • initramfs (ramdisk boot)
# • GRUB config files
# • DOIT être non-chiffré (BIOS lit avant OS)
# • ext4 filesystem

# /dev/sda3 (/) - Reste disque:
# • Root filesystem (tout OS Ubuntu)
# • /home, /var, /usr, /opt, /tmp
# • ext4 filesystem (default)
# • Alternatives: xfs (performance), btrfs (snapshots)

# Swap:
# • Mémoire virtuelle (RAM overflow)
# • Size = 1GB pour VM 2GB RAM (rule of thumb: 50% RAM)
# • Fichier /swapfile vs partition: Équivalent performance
# • Utilisé si RAM saturée (avoid!)


# FILESYSTEM TYPES:
# ════════════════

# ext4 (default):
# • Journaled filesystem mature
# • Excellent performance générale
# • Gestion 1EB max, fichiers 16TB
# • Recommandé 99% cas

# xfs:
# • Haute performance large files
# • Excellent multi-threading
# • Databases, video editing
# • Pas resize shrink (grow only)

# btrfs:
# • Copy-on-write (COW)
# • Snapshots intégrés
# • Compression transparente
# • Moins mature qu'ext4


# RECOMMANDATION POUR CE GUIDE:
# ════════════════════════════

# -> Choisir "Use entire disk" SANS LVM/LUKS
# Raisons:
# • Simplicité maximale pour apprentissage
# • Performance optimale
# • Pas besoin LVM pour VM 20GB
# • LUKS inutile pour lab (pas data sensible)
# • Changeable en recréant VM si besoin

# PROCESS:
# 1. Sélectionner ( ) Use an entire disk
# 2. Décocher [ ] Set up this disk as an LVM group
# 3. Décocher [ ] Encrypt LVM with LUKS
# 4. Vérifier disque sélectionné: SCSI3 NVME VMware Virtual disk 20G

# -> [Done] -> [Enter]


# ÉCRAN 8.5/14: CONFIRMATION LAYOUT STOCKAGE
# ──────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Storage configuration                         │
# │                                                │
# │  USED DEVICES:                                 │
# │  SCSI3 NVME VMware Virtual disk               │
# │                                                │
# │  FILE SYSTEM SUMMARY:                          │
# │  MOUNT POINT   SIZE      TYPE    DEVICE        │
# │  /boot/efi     1.049GB   fat32   /dev/sda1     │
# │  /             18.463GB  ext4    /dev/sda2     │
# │                                                │
# │  The following devices will be formatted:      │
# │  • /dev/sda as GPT                             │
# │  • /dev/sda1 as EFI System Partition           │
# │  • /dev/sda2 as ext4 root filesystem           │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI cet écran confirmation?
# • Dernière chance vérifier avant formatage
# • Formatage = DESTRUCTION données disque
# • Une fois [Done], retour arrière impossible

# VÉRIFICATIONS:
# ═════════════

# [OK] Disque correct: VMware Virtual disk 20G
# [OK] Partition boot: /dev/sda1 ~1GB (suffisant kernel)
# [OK] Partition root: /dev/sda2 ~18-19GB (reste disque)
# [OK] Filesystem type: ext4 (standard, fiable)
# [OK] Mount points: /boot/efi et / (minimum requis)

# GPT vs MBR:
# • GPT = GUID Partition Table (moderne)
# • MBR = Master Boot Record (legacy)
# • Ubuntu choisit GPT automatiquement (support disques >2TB)
# • VM BIOS boot: Fonctionne avec les deux
# • VM UEFI boot: Requiert GPT obligatoirement

# EFI SYSTEM PARTITION:
# • Requis pour UEFI boot
# • Stocke bootloaders UEFI
# • FAT32 filesystem (spec UEFI)
# • VMware Workstation default: BIOS boot (pas EFI)
# • Mais Ubuntu crée partition EFI quand même (compatibilité)

# ANALOGIE:
# Formatage disque = Démolir maison pour reconstruire
# • Blueprints (partitions) dessinés
# • Matériaux (filesystem) choisis
# • Une fois bulldozer démarré -> Point de retour

# ERREUR SI DOUTE:
# • [Back] -> Revenir config stockage
# • Vérifier options sélectionnées
# • Re-valider avec [Done]

# -> VÉRIFIER résumé -> [Done] -> [Enter]


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 9/14: PROFIL UTILISATEUR
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Profile setup                                 │
# │                                                │
# │  Your name:      [John Doe                 ]   │
# │                                                │
# │  Your server's name:                           │
# │                  [ubuntu-server             ]   │
# │                                                │
# │  Pick a username:                              │
# │                  [johndoe                   ]   │
# │                                                │
# │  Choose a password:                            │
# │                  [******************         ]   │
# │                                                │
# │  Confirm your password:                        │
# │                  [******************         ]   │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI ces informations?
# • Créer compte utilisateur principal (non-root)
# • Définir hostname machine (identification réseau)
# • Sécuriser accès système avec mot de passe

# CHAMP PAR CHAMP:
# ═══════════════

# 1. YOUR NAME (Nom complet):
# • Nom réel utilisateur (John Doe, Marie Dupont)
# • Purement informatif (GECOS field)
# • Visible dans: finger, who, mail headers
# • Peut contenir espaces, accents
# • Exemple: "Jean-Pierre Dubois"

# 2. YOUR SERVER'S NAME (Hostname):
# • Nom machine sur réseau
# • Visible dans: prompt bash, DHCP, DNS
# • Règles:
#   - Minuscules obligatoires
#   - Pas d'espaces
#   - Caractères: a-z, 0-9, - (tiret)
#   - Max 63 caractères
#   - Commence par lettre
# • Conventions entreprise:
#   ubuntu-web-01 (rôle + numéro)
#   srv-db-prod-01 (environnement)
#   vmtest-johndoe (owner)
# • Exemple: ubuntu-server, web-server-01, test-vm

# HOSTNAME IMPACT:
# Fichiers affectés:
# • /etc/hostname: ubuntu-server
# • /etc/hosts: 127.0.1.1 ubuntu-server
# • Prompt bash: johndoe@ubuntu-server:~$
# • Logs système: ubuntu-server kernel: [...]

# ERREUR COMMUNE HOSTNAME:
# [X] Utiliser espaces: "Ubuntu Server" -> Erreur
# [X] Majuscules: "Ubuntu-Server" -> Corrigé en minuscules
# [X] Caractères spéciaux: "ubuntu_server@01" -> Invalide
# [OK] Correct: ubuntu-server-01, test-vm, webserver

# 3. PICK A USERNAME (Login):
# • Nom connexion SSH, login console
# • Membre groupe sudo (droits admin)
# • Règles strictes:
#   - Minuscules uniquement
#   - Commence par lettre
#   - Caractères: a-z, 0-9, - _ (tiret underscore)
#   - Max 32 caractères
#   - Pas de mots réservés (root, admin, test)
# • UID assigné: 1000 (premier utilisateur)
# • Home directory: /home/username

# USERNAME CONVENTIONS:
# • Prénom: john, marie, pierre
# • Prenom.nom: john.doe, marie.dupont
# • Format court: jdoe, mdupont
# • Format entreprise: Varie selon politique
# • Éviter: admin, user, test (génériques)

# ERREUR COMMUNE USERNAME:
# [X] Majuscules: "JohnDoe" -> Refusé
# [X] Email: "john@company.com" -> Invalide (@)
# [X] Espaces: "john doe" -> Refusé
# [OK] Correct: johndoe, john.doe, jdoe, j_doe

# 4. CHOOSE PASSWORD:
# • Mot de passe compte utilisateur
# • Requis pour: login, sudo, su
# • Minimum 8 caractères (recommandé 12+)
# • Complexité: Non forcée par défaut (mais recommandée!)

# BONNES PRATIQUES PASSWORD:
# [OK] Longueur: 12-16 caractères minimum
# [OK] Mixte: Majuscules, minuscules, chiffres, symboles
# [OK] Pas de mots dictionnaire
# [OK] Unique (pas réutilisé ailleurs)
# [OK] Mémorisable mais complex

# TECHNIQUES GÉNÉRATION:
# • Passphrase: "J'aime3PommesRouges!" (14 chars, mémorable)
# • Random: "Kp#9mL@2xR$5" (générateur password)
# • Diceware: "correct-horse-battery-staple" (mots aléatoires)

# MAUVAIS PASSWORDS (ÉVITER ABSOLUMENT):
# [X] password123
# [X] admin
# [X] ubuntu
# [X] 12345678
# [X] qwerty
# [X] VotreNom123
# [X] Date naissance (01011990)

# BONS PASSWORDS EXEMPLES:
# [OK] MyS3cur3P@ssw0rd!
# [OK] J'aim3-L3s-Fr!tes
# [OK] W0nd3rful_Tr33s#42
# [OK] Correct-Horse-Battery-99!

# PASSWORD LAB vs PRODUCTION:
# • Lab/testing: Peut être simple (MyPassword123)
# • Production: DOIT être complexe + politique rotation

# 5. CONFIRM PASSWORD:
# • Retaper mot de passe identique
# • Validation: Les 2 doivent matcher exactement
# • Si mismatch -> Erreur "Passwords do not match"

# VÉRIFICATION AVANT VALIDER:
# ═════════════════════════════

# • Username mémorisé: Noter sur papier/keepass!
# • Password mémorisé: Tester dans notepad si pas sûr
# • Hostname logique: Reflet usage VM
# • Pas de typo dans username (correction impossible!)

# CHANGEMENT POST-INSTALLATION:
# • Password: passwd (commande)
# • Username: usermod -l (compliqué, éviter)
# • Hostname: hostnamectl set-hostname (facile)
# • Nom complet: chfn (finger utility)

# RECOMMANDATION LAB:
# Your name: Admin Test
# Hostname: ubuntu-server (ou ubuntu-web, ubuntu-db selon usage)
# Username: adminuser (ou votre prénom)
# Password: MyLabP@ss123 (simple mais respecte complexité)

# ANALOGIE SÉCURITÉ:
# Password = Clé maison
# • Faible (password) = Serrure cassable enfant
# • Moyen (MyPassword1) = Cadenas standard
# • Fort (W0nd3r#Tree$42) = Serrure haute sécurité

# -> Remplir tous champs -> [Done] -> [Enter]


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 10/14: UBUNTU PRO
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Upgrade to Ubuntu Pro                         │
# │                                                │
# │  Ubuntu Pro provides additional security       │
# │  updates and compliance features.              │
# │                                                │
# │  • Extended Security Maintenance (10 years)    │
# │  • FIPS 140-2 Level 1 certified crypto         │
# │  • Common Criteria EAL2 certification          │
# │  • Kernel Livepatch (no reboot updates)        │
# │  • Optional: Landscape systems management      │
# │                                                │
# │  Free for personal use (up to 5 machines)      │
# │  Paid for enterprise                           │
# │                                                │
# │  [ ] Set up Ubuntu Pro                         │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI Ubuntu Pro?
# • Ubuntu standard: 5 ans support (Main + Security)
# • Ubuntu Pro: 10 ans support (Extended Security Maintenance)
# • Compliance: FIPS, Common Criteria (gouvernements, banques)
# • Livepatch: Patcher kernel sans reboot (uptime critique)

# QUAND UTILISER UBUNTU PRO:
# ═════════════════════════

# USE CASES PRO:
# [OK] Serveurs production (ESM 10 ans)
# [OK] Compliance réglementaire (HIPAA, GDPR, PCI-DSS)
# [OK] Environnements haute disponibilité (Livepatch)
# [OK] Gouvernement (FIPS crypto)
# [OK] Entreprise (support Canonical officiel)

# PAS REQUIS SI:
# [X] Lab/testing personnel
# [X] VM courte durée
# [X] Pas contraintes compliance
# [X] Reboot acceptable pour patches

# FEATURES UBUNTU PRO DÉTAIL:
# ══════════════════════════

# 1. ESM (Extended Security Maintenance):
# • Ubuntu standard: 5 ans patches Main repository
# • Ubuntu Pro: +5 ans patches (total 10 ans)
# • Couvre 23,000+ packages Universe repository
# • Exemple: Ubuntu 20.04 LTS
#   - Standard support: 2020 -> 2025
#   - ESM support: 2020 -> 2030

# 2. FIPS Crypto:
# • FIPS 140-2 Level 1 certified
# • Modules crypto validés (OpenSSL, Kernel crypto)
# • Requis: Gouvernement US, secteur défense
# • Impact: Désactive algos non-certifiés

# 3. Common Criteria EAL2:
# • Certification sécurité internationale
# • ISO/IEC 15408 compliant
# • Requis: Europe secteur public

# 4. Livepatch:
# • Patch kernel sans reboot
# • Application patches sécurité à chaud
# • Uptime: 99.99% vs 99.9% (reboots mensuels)
# • Limite: Patches critiques uniquement (pas features)

# 5. Landscape (Optional):
# • Management centralisé multi-machines
# • Dashboard web Ubuntu servers
# • Deploy packages, scripts, policies
# • Monitoring, alerting, compliance reports
# • Alternative gratuite: Ansible, Chef, Puppet

# PRICING UBUNTU PRO:
# ═════════════════

# Personal use:
# • FREE jusqu'à 5 machines
# • Activation via Ubuntu One account
# • Attacher token lors installation ou post-install

# Enterprise:
# • ~$25/an par machine (support Essential)
# • ~$225/an par machine (support Standard)
# • ~$750/an par machine (support Advanced)
# • Volume pricing pour 100+ machines

# ACTIVATION PROCESS SI COCHÉE:
# 1. Créer Ubuntu One account (SSO Canonical)
# 2. Obtenir Pro token (dashboard)
# 3. Installer: ubuntu-advantage-tools package
# 4. Attacher: sudo ua attach <TOKEN>
# 5. Enable features: sudo ua enable esm livepatch

# IMPACT PERFORMANCE:
# • Livepatch: ~1-2% overhead CPU (monitoring kernel)
# • FIPS crypto: ~5-15% overhead (crypto validé plus lent)
# • ESM: Aucun (juste plus de repos packages)

# RECOMMANDATION DÉBUTANT:
# -> DÉCOCHER "Set up Ubuntu Pro"
# Raisons:
# • Pas requis pour apprentissage
# • Lab VM durée de vie courte
# • Configuration additionnelle requise
# • Activable post-installation si besoin
# • Free tier 5 machines = Généreux mais inutile ici

# ACTIVATION POST-INSTALL:
# Si changement d'avis:
# $ sudo apt install ubuntu-advantage-tools
# $ sudo ua attach <votre-token>
# $ sudo ua enable esm-infra livepatch

# -> Laisser décochée -> [Done] -> [Enter]


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 11/14: CONFIGURATION SSH
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  SSH Setup                                     │
# │                                                │
# │  [X] Install OpenSSH server                    │
# │                                                │
# │  You can import your SSH keys from:            │
# │                                                │
# │  ( ) GitHub                                    │
# │      Username: [                          ]    │
# │                                                │
# │  ( ) Launchpad                                 │
# │      Username: [                          ]    │
# │                                                │
# │  ( ) No imported SSH keys                      │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI installer OpenSSH?
# • SSH = Secure Shell (protocole connexion distante)
# • Essentiel pour gérer serveur à distance
# • Alternative telnet (non-chiffré, obsolète)
# • Port 22 par défaut
# • Service: sshd (SSH daemon)

# QUAND installer SSH:
# [OK] TOUJOURS pour serveur (headless)
# [OK] VM sans interface graphique
# [OK] Gestion à distance depuis hôte
# [X] Desktop Ubuntu avec GUI (optional)

# INSTALL OPENSSH SERVER:
# ═════════════════════════

# SI COCHÉE (recommandé):
# Package installé: openssh-server
# • Service: sshd démarre automatiquement
# • Port: 22/TCP écouté
# • Config: /etc/ssh/sshd_config
# • Logs: /var/log/auth.log
# • Size: ~500KB

# SI NON-COCHÉE:
# • Pas SSH disponible
# • Installation manuelle post-install:
#   $ sudo apt update
#   $ sudo apt install openssh-server
#   $ sudo systemctl enable --now ssh

# IMPORT SSH KEYS:
# ═══════════════

# POURQUOI importer clés SSH?
# • Authentication sans password
# • Connexion plus rapide et sécurisée
# • Automatisation scripts (Ansible, etc.)
# • Best practice production

# OPTIONS IMPORT:
# 1. GitHub:
#    • Import depuis github.com/username.keys
#    • URL: https://github.com/<username>.keys
#    • Requiert: GitHub account avec SSH keys uploadées
#    • Exemple: https://github.com/torvalds.keys

# 2. Launchpad:
#    • Import depuis launchpad.net/~username/+sshkeys
#    • Service Canonical (Ubuntu development)
#    • Moins populaire que GitHub
#    • Exemple: https://launchpad.net/~user/+sshkeys

# 3. No imported keys:
#    • Pas import automatique
#    • Login initial par password
#    • Ajout clés manuel plus tard
#    • Recommandé si pas clés prêtes

# COMMENT FONCTIONNENT SSH KEYS:
# ═════════════════════════════

# Paire de clés asymétriques:
# • Clé privée (id_rsa): GARDER SECRET (jamais partager!)
# • Clé publique (id_rsa.pub): Distribuer librement

# Authentication process:
# 1. Client envoie clé publique à serveur
# 2. Serveur vérifie présence clé dans ~/.ssh/authorized_keys
# 3. Serveur génère challenge chiffré avec clé publique
# 4. Client déchiffre avec clé privée
# 5. Si succès -> Connexion autorisée (pas de password!)

# EXEMPLE GÉNÉRATION CLÉ (sur client):
# $ ssh-keygen -t rsa -b 4096 -C "mon-email@example.com"
# • Génère: ~/.ssh/id_rsa (privée) et ~/.ssh/id_rsa.pub (publique)
# • Passphrase: Protège clé privée (optionnel mais recommandé)

# EXEMPLE IMPORT MANUEL (post-install):
# Sur client Windows/Linux/Mac:
# $ ssh-copy-id adminuser@192.168.120.128
# • Copie clé publique locale vers serveur Ubuntu
# • Ajoute dans: /home/adminuser/.ssh/authorized_keys

# STRUCTURE FICHIER authorized_keys:
# ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC... john@laptop
# ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQD... jane@desktop
# • Une clé par ligne
# • Permet multiple clients connexion même compte

# SÉCURITÉ SSH KEYS vs PASSWORD:
# ═══════════════════════════════

# SSH Keys:
# [OK] Plus sécurisé (4096-bit RSA = 2^4096 combinaisons)
# [OK] Pas brute-force possible
# [OK] Révocable (supprimer ligne authorized_keys)
# [OK] Automation-friendly
# [X] Gestion clés requise
# [X] Clé privée compromise = accès total

# Password:
# [OK] Simple comprendre
# [OK] Pas fichier à gérer
# [X] Brute-force possible
# [X] Transmission réseau (même si chiffré)
# [X] Phishing/shoulder-surfing vulnérable

# BEST PRACTICE PRODUCTION:
# 1. Installer OpenSSH [OK]
# 2. Importer SSH keys [OK]
# 3. Désactiver password login:
#    /etc/ssh/sshd_config:
#    PasswordAuthentication no
# 4. Changer port SSH (22 -> 2222):
#    Port 2222
# 5. Désactiver root login:
#    PermitRootLogin no

# RECOMMANDATION DÉBUTANT:
# -> COCHER "Install OpenSSH server"
# -> SÉLECTIONNER "No imported SSH keys"
# Raisons:
# • OpenSSH essentiel serveur
# • Import keys plus tard une fois compris
# • Login password initial OK pour lab
# • Progression apprentissage naturelle

# CONNEXION SSH APRÈS INSTALL:
# Sur Windows (PowerShell/CMD):
# > ssh adminuser@192.168.120.128

# Sur Linux/Mac (Terminal):
# $ ssh adminuser@192.168.120.128

# Première connexion:
# The authenticity of host '192.168.120.128' can't be established.
# ECDSA key fingerprint is SHA256:abc123...
# Are you sure you want to continue (yes/no)? yes
# adminuser@192.168.120.128's password: [entrer password]

# TROUBLESHOOTING CONNEXION:
# Erreur: "Connection refused"
# -> Vérifier sshd actif: systemctl status ssh
# -> Vérifier firewall: sudo ufw status (si activé)

# Erreur: "Permission denied"
# -> Vérifier username correct
# -> Vérifier password correct
# -> Vérifier /etc/ssh/sshd_config PasswordAuthentication yes

# -> Cocher OpenSSH, sélectionner No keys -> [Done] -> [Enter]


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 12/14: FEATURED SERVER SNAPS
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Featured Server Snaps                         │
# │                                                │
# │  These are popular snaps in server             │
# │  environments. Select snaps to install.        │
# │                                                │
# │  [ ] docker           Container platform       │
# │  [ ] microk8s         Lightweight Kubernetes   │
# │  [ ] lxd              System containers        │
# │  [ ] nextcloud        Private cloud storage    │
# │  [ ] mosquitto        MQTT broker             │
# │  [ ] postgresql       PostgreSQL database      │
# │                                                │
# │            [Done]   [Back]                     │
# └────────────────────────────────────────────────┘

# POURQUOI cet écran?
# • Snaps = Paquets universels Canonical
# • Installation simplifiée logiciels populaires
# • Auto-update automatique
# • Isolation applications (sécurité)
# • Alternative: APT packages traditionnels

# QU'EST-CE QU'UN SNAP?
# ═════════════════════

# Définition:
# • Format package universel Ubuntu (et autres distros)
# • Contient: App + dépendances + runtime
# • Sandboxé: Isolation avec AppArmor
# • Immutable: Pas modification app installée
# • Updates automatiques quotidiennes

# SNAP vs APT:
# ╔════════════════╦═══════════╦══════════════╗
# ║ Feature        ║ SNAP      ║ APT          ║
# ╠════════════════╬═══════════╬══════════════╣
# ║ Dependencies   ║ Incluses  ║ Partagées    ║
# ║ Updates        ║ Auto      ║ Manuel       ║
# ║ Isolation      ║ Yes       ║ No           ║
# ║ Size           ║ Large     ║ Small        ║
# ║ Startup        ║ Slower    ║ Faster       ║
# ║ Versions       ║ Latest    ║ Stable       ║
# ╚════════════════╩═══════════╩══════════════╝

# AVANTAGES SNAPS:
# [OK] Installation simplifiée (snap install docker)
# [OK] Updates automatiques (sécurité)
# [OK] Rollback possible (snap revert)
# [OK] Channels versions (stable, candidate, edge)
# [OK] Isolation sécurité (confined)

# INCONVÉNIENTS SNAPS:
# [X] Size large (~500MB pour Docker snap)
# [X] Startup lent (mount squashfs)
# [X] Pas de customisation profonde
# [X] Dépendance snapd service
# [X] Controverse communauté (pas 100% open)


# SNAPS DISPONIBLES DÉTAIL:
# ═════════════════════════

# 1. DOCKER:
# Description: Container platform
# • Alternative: apt install docker.io docker-compose
# • Snap size: ~500MB
# • Use case: Run containers applications
# • Commandes: docker run, docker-compose up
# • Production: APT préféré (contrôle total)

# 2. MICROK8S:
# Description: Lightweight Kubernetes
# • Full Kubernetes single-node
# • Alternative: kubeadm, k3s, kind
# • Snap size: ~800MB
# • Use case: Local Kubernetes development
# • Commandes: microk8s kubectl, microk8s status
# • Note: Snap RECOMMANDÉ pour microk8s (méthode officielle)

# 3. LXD:
# Description: System containers (Linux Containers)
# • Alternative: docker (app containers)
# • Containers full OS (Ubuntu, Alpine, etc.)
# • Snap size: ~300MB
# • Use case: Multi-tenant hosting, dev environments
# • Commandes: lxc launch, lxc list
# • Note: Ubuntu pré-installe parfois LXD

# 4. NEXTCLOUD:
# Description: Self-hosted cloud storage
# • Alternative: ownCloud, Seafile
# • Snap size: ~1GB (inclut PHP, MariaDB, Apache)
# • Use case: Private Dropbox/Google Drive
# • Interface: Web UI port 80/443
# • Note: Snap EXCELLENT pour Nextcloud (tout-en-un)

# 5. MOSQUITTO:
# Description: MQTT broker
# • Protocol IoT messaging (pub/sub)
# • Alternative: apt install mosquitto
# • Snap size: ~50MB
# • Use case: IoT devices communication
# • Ports: 1883 (MQTT), 8883 (MQTT over TLS)

# 6. POSTGRESQL:
# Description: SQL database
# • Alternative: apt install postgresql
# • Snap size: ~200MB
# • Use case: Relational database
# • Port: 5432
# • Note: APT généralement préféré (intégration systèm)


# QUAND INSTALLER CES SNAPS:
# ═════════════════════════

# MAINTENANT (pendant install):
# [OK] Si besoin immédiat après install
# [OK] Microk8s (snap méthode recommandée)
# [OK] Nextcloud (all-in-one facile)
# [X] Non si besoin évaluer options install

# PLUS TARD (post-install):
# [OK] Plus de contrôle (APT vs Snap)
# [OK] Évaluation taille vs bénéfices
# [OK] Test performance snap vs native
# [OK] Configuration précise possible

# RECOMMANDATION PAR SNAP:
# ═══════════════════════

# Docker: [X] SKIP
# • APT meilleur (docker.io package)
# • Plus léger, start plus rapide
# • Install post: sudo apt install docker.io

# MicroK8s: [OK] OK SI BESOIN K8s
# • Snap méthode officielle
# • Mais skip si pas besoin Kubernetes maintenant

# LXD: [X] SKIP
# • Déjà installé si Ubuntu Server standard
# • Complexe pour débutant
# • Apprendre Docker d'abord

# Nextcloud: [OK] OK SI BESOIN CLOUD
# • Snap excellent pour Nextcloud
# • All-in-one parfait
# • Mais skip si focus apprentissage Linux

# Mosquitto: [X] SKIP
# • Niche use case (IoT)
# • APT suffisant si besoin

# PostgreSQL: [X] SKIP
# • APT préféré (contrôle, performance)
# • Install post: sudo apt install postgresql


# GESTION SNAPS POST-INSTALL:
# ══════════════════════════

# Lister snaps installés:
# $ snap list
# Name        Version    Rev   Tracking       Publisher
# core22      20230502   634   latest/stable  canonical
# docker      20.10.24   2746  latest/stable  canonical

# Installer snap:
# $ sudo snap install docker

# Supprimer snap:
# $ sudo snap remove docker

# Update snap manuel:
# $ sudo snap refresh docker

# Voir updates disponibles:
# $ snap refresh --list

# Désactiver auto-updates:
# $ sudo snap set system refresh.retain=2
# $ sudo snap refresh --hold docker

# Rollback version précédente:
# $ sudo snap revert docker


# ESPACE DISQUE CONSIDÉRATION:
# ═══════════════════════════

# Snaps multiples = Espace significatif:
# • Docker: ~500MB
# • MicroK8s: ~800MB
# • Nextcloud: ~1GB
# • Total: ~2.3GB (sur disque 20GB = 11.5%)

# VM 20GB breakdown après snaps:
# • OS: ~5GB
# • Snaps: ~2.3GB
# • Disponible: ~12.7GB

# ALTERNATIVE POST-INSTALL:
# APT packages:
# $ sudo apt install docker.io postgresql mosquitto
# • Total: ~200-300MB vs 700-800MB snaps
# • Économie: ~400-500MB


# RECOMMANDATION DÉBUTANT:
# -> DÉCOCHER TOUS LES SNAPS
# Raisons:
# • Focus apprentissage Linux basique d'abord
# • Installation sélective plus tard selon besoin
# • Économie espace disque
# • Comprendre différence APT vs Snap avant choisir
# • Éviter surcharge VM avec services inutilisés

# PROGRESSION APPRENTISSAGE:
# Étape 1: OS Ubuntu de base (maintenant)
# Étape 2: Maîtriser shell, filesystems, networking
# Étape 3: Installer Docker (APT ou Snap selon besoin)
# Étape 4: Apprendre containers
# Étape 5: Éventuellement K8s (MicroK8s snap)

# -> Tout décocher -> [Done] -> [Enter]


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 13/14: INSTALLATION EN COURS
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Installing system                             │
# │                                                │
# │  [██████████████████░░░░░░░░░░░] 60%           │
# │                                                │
# │  Current task:                                 │
# │  [BLACK_RIGHT-POINTING_POINTER] Installing kernel                           │
# │                                                │
# │  Recent tasks:                                 │
# │  [OK] Formatting partitions                       │
# │  [OK] Installing base system                      │
# │  [OK] Configuring network                         │
# │  [BLACK_RIGHT-POINTING_POINTER] Installing kernel                           │
# │    Installing bootloader                       │
# │    Configuring users                           │
# │                                                │
# │  Estimated time remaining: 8 minutes           │
# └────────────────────────────────────────────────┘

# QUE SE PASSE-T-IL MAINTENANT?
# ════════════════════════════

# PHASE 1: FORMATAGE PARTITIONS (0-10%)
# • Création table partitions GPT sur /dev/sda
# • Formatage /dev/sda1 en FAT32 (EFI partition)
# • Formatage /dev/sda2 en ext4 (root filesystem)
# • Création filesystems: mkfs.ext4, mkfs.fat
# • Durée: ~1-2 minutes
# • Détails technique:
#   $ mkfs.ext4 -L cloudimg-rootfs /dev/sda2
#   $ mkfs.fat -F32 -n ESP /dev/sda1

# PHASE 2: INSTALLATION BASE SYSTEM (10-40%)
# • Extraction archive base Ubuntu Server
# • Packages essentiels: ~250-500 packages
# • Binaries: bash, coreutils, systemd, apt, dpkg
# • Libraries: libc6, libssl, libgcc
# • Taille: ~2-3GB données copiées
# • Durée: ~3-5 minutes
# • Source: /cdrom/pool/ (ISO monté)

# PACKAGES BASE INSTALLÉS:
# Essential:
# • bash, dash (shells)
# • coreutils (ls, cp, mv, rm, cat, etc.)
# • systemd (init system)
# • apt, dpkg (package management)
# • openssh-server (si sélectionné)

# Important:
# • linux-image-generic (kernel)
# • grub-pc (bootloader)
# • netplan.io (network config)
# • cloud-init (provisioning)
# • vim-tiny, nano (editors)

# PHASE 3: CONFIGURATION RÉSEAU (40-50%)
# • Génération /etc/netplan/00-installer-config.yaml
# • Configuration DHCP/Static selon choix
# • Hostname: /etc/hostname + /etc/hosts
# • DNS: /etc/resolv.conf (via systemd-resolved)
# • Durée: ~30 secondes

# Fichier netplan créé:
# network:
#   version: 2
#   ethernets:
#     ens33:
#       dhcp4: true

# PHASE 4: INSTALLATION KERNEL (50-70%)
# • Copie kernel: /boot/vmlinuz-6.8.0-31-generic
# • Initramfs: /boot/initrd.img-6.8.0-31-generic
# • Modules kernel: /lib/modules/6.8.0-31-generic/
# • Headers: linux-headers (si requis compilation)
# • Durée: ~2-3 minutes
# • Taille kernel: ~250MB (vmlinuz + initramfs + modules)

# PHASE 5: INSTALLATION BOOTLOADER (70-80%)
# • GRUB2 installation dans MBR/EFI
# • Génération /boot/grub/grub.cfg
# • Configuration boot order
# • Update-grub exécuté
# • Durée: ~1 minute
# • Commande équivalente: grub-install /dev/sda

# PHASE 6: CONFIGURATION UTILISATEURS (80-90%)
# • Création user account (adminuser)
# • Hash password (SHA-512): /etc/shadow
# • Ajout groupe sudo: /etc/group
# • Home directory: /home/adminuser
# • Shell default: /bin/bash
# • UID 1000, GID 1000 (premier utilisateur)
# • Durée: ~30 secondes

# Fichiers modifiés:
# • /etc/passwd: adminuser:x:1000:1000:Admin Test:/home/adminuser:/bin/bash
# • /etc/shadow: adminuser:$6$rounds=656000$... (hash password)
# • /etc/group: sudo:x:27:adminuser

# PHASE 7: CONFIGURATION SERVICES (90-95%)
# • Enable systemd services:
#   - systemd-networkd
#   - systemd-resolved
#   - ssh (openssh-server)
#   - cloud-init (si applicable)
# • Création symbolic links: /etc/systemd/system/
# • Durée: ~30 secondes

# PHASE 8: INSTALLATION SNAPS (95-98%)
# • Si snaps sélectionnés: Installation via snapd
# • Pre-seed snap core et core22
# • Configure snap auto-update
# • Durée: ~1-2 minutes par snap
# • Skip si aucun snap sélectionné

# PHASE 9: FINALISATION (98-100%)
# • Nettoyage fichiers temporaires
# • Sync filesystem (flush cache)
# • Unmount ISO /cdrom
# • Update GRUB boot order
# • Configuration cloud-init (si applicable)
# • Logs installation: /var/log/installer/
# • Durée: ~30 secondes


# CE QUI EST VISIBLE PENDANT INSTALL:
# ═══════════════════════════════════

# Messages défilants (tail -f style):
# Extracting templates from packages: 100%
# Preconfiguring packages ...
# Selecting previously unselected package systemd
# Preparing to unpack .../systemd_251.4-1ubuntu7_amd64.deb ...
# Unpacking systemd (251.4-1ubuntu7) ...
# Setting up systemd (251.4-1ubuntu7) ...
# Created symlink /etc/systemd/system/multi-user.target.wants/systemd-networkd.service
# Processing triggers for initramfs-tools ...
# update-initramfs: Generating /boot/initrd.img-6.8.0-31-generic

# PROGRESS BAR CALCUL:
# • Basé sur nombre packages à installer
# • Pas linéaire: Kernel installation = 20% progress mais 30% temps
# • "Estimated time" = Approximation (variable selon CPU/disk VM)


# ACTIVITÉ SYSTÈME PENDANT INSTALL:
# ═════════════════════════════════

# CPU Usage:
# • 60-90% utilisation (décompression packages, hash passwords)
# • Pics lors: Extraction archives, update-initramfs

# Disk I/O:
# • Writes intensifs: 2-5GB écrits sur -flat.vmdk
# • Sequential writes principalement (efficace)

# RAM Usage:
# • 500MB-1GB utilisés
# • Ramdisk /tmp contient fichiers temporaires

# Network:
# • Si proxy configuré: Downloads packages
# • Si snaps sélectionnés: Downloads de snapd store
# • Si miroir archive.ubuntu.com: ~100-500MB téléchargés


# ERREURS POSSIBLES ET SOLUTIONS:
# ═══════════════════════════════

# Erreur: "Failed to download package xxx"
# Cause: Réseau non disponible, miroir injoignable
# Solution: Vérifier config réseau, tester ping 8.8.8.8
# -> [Back] -> Reconfigurer réseau

# Erreur: "Not enough disk space"
# Cause: Partition trop petite
# Solution: Augmenter taille disque VM (20GB minimum)
# -> Redémarrer installation avec disque plus grand

# Erreur: "Unable to install GRUB"
# Cause: BIOS vs UEFI mismatch, partition EFI manquante
# Solution: Vérifier VM settings BIOS mode
# -> [Back] -> Revoir config stockage

# Erreur: "Failed to configure network"
# Cause: Conflit IP, gateway inaccessible
# Solution: Vérifier VMware NAT service actif
# -> [Back] -> Reconfigurer réseau en DHCP


# QUE FAIRE PENDANT L'INSTALLATION:
# ═════════════════════════════════

# [OK] ATTENDRE PATIEMMENT (~10-15 minutes total)
# [OK] Observer messages pour comprendre processus
# [OK] Vérifier progress bar avance régulièrement
# [OK] NE PAS:
#   [X] Fermer fenêtre VM
#   [X] Power off VM
#   [X] Suspendre VM
#   [X] Redémarrer hôte

# ANALOGIE:
# Installation Ubuntu = Construction maison
# • Fondations (partitions) -> 10%
# • Murs/structure (base system) -> 40%
# • Plomberie (network) -> 10%
# • Électricité (kernel) -> 20%
# • Portes/fenêtres (bootloader) -> 10%
# • Peinture (users/services) -> 10%


# FICHIERS LOGS INSTALLATION:
# ══════════════════════════

# Post-installation, consulter:
# /var/log/installer/autoinstall-user-data
# /var/log/installer/curtin-install.log
# /var/log/installer/subiquity-server-debug.log

# Utile pour:
# • Debugging problèmes
# • Audit installation
# • Automatisation future (cloud-init)


# -> ATTENDRE COMPLÉTION 100% -> Passage automatique écran suivant


# ────────────────────────────────────────────────────────────────────
# ÉCRAN 14/14: INSTALLATION TERMINÉE
# ────────────────────────────────────────────────────────────────────

# INTERFACE:
# ┌────────────────────────────────────────────────┐
# │  Installation complete!                        │
# │                                                │
# │  [████████████████████████████████████] 100%   │
# │                                                │
# │  [OK] System installed successfully               │
# │  [OK] Bootloader configured                       │
# │  [OK] Users created                               │
# │  [OK] Network configured                          │
# │  [OK] OpenSSH server installed                    │
# │                                                │
# │  You must reboot for the installation to       │
# │  be complete.                                  │
# │                                                │
# │            [Reboot Now]                        │
# └────────────────────────────────────────────────┘

# POURQUOI REBOOT REQUIS?
# • Installation faite sur disque virtuel (sda)
# • Actuellement: Système tourne depuis ISO (ramdisk)
# • Reboot: Charge système depuis disque installé
# • ISO sera éjecté automatiquement post-reboot

# QU'A FAIT L'INSTALLATEUR?
# ═════════════════════════

# FICHIERS SYSTÈME CRÉÉS:
# ├── /boot/
# │   ├── vmlinuz-6.8.0-31-generic (kernel Linux)
# │   ├── initrd.img-6.8.0-31-generic (ramdisk boot)
# │   ├── grub/ (bootloader config)
# │   └── efi/ (si UEFI)
# ├── /etc/
# │   ├── hostname (ubuntu-server)
# │   ├── hosts (résolution noms locaux)
# │   ├── fstab (mount points automatiques)
# │   ├── netplan/ (config réseau)
# │   ├── ssh/ (config OpenSSH)
# │   ├── passwd, shadow, group (users database)
# │   └── apt/ (sources packages)
# ├── /home/
# │   └── adminuser/ (home directory utilisateur)
# │       ├── .bashrc (shell config)
# │       ├── .profile (env variables)
# │       └── .ssh/ (clés SSH si configurées)
# ├── /var/
# │   ├── log/ (logs système)
# │   ├── cache/apt/ (cache packages)
# │   └── lib/apt/ (database packages installés)
# └── /usr/
#     ├── bin/ (binaries essentiels)
#     ├── sbin/ (binaries admin)
#     └── lib/ (libraries système)

# TAILLE DISQUE FINALE:
# $ df -h
# Filesystem      Size  Used Avail Use% Mounted on
# /dev/sda2        19G  4.8G   13G  28% /
# /dev/sda1       1.1G  6.1M  1.1G   1% /boot/efi
# tmpfs           997M     0  997M   0% /dev/shm

# PACKAGES INSTALLÉS:
# $ dpkg -l | wc -l
# ~500 packages (Standard install)
# ~250 packages (Minimized install)

# SERVICES ACTIFS:
# $ systemctl list-units --type=service --state=running
# • systemd-networkd.service (gestion réseau)
# • systemd-resolved.service (DNS résolution)
# • ssh.service (OpenSSH server)
# • cron.service (scheduled tasks)
# • systemd-journald.service (logging)
# • dbus.service (inter-process communication)


# VÉRIFICATIONS AVANT REBOOT:
# ══════════════════════════

# [OK] Message "Installation complete!" affiché
# [OK] Progress bar 100%
# [OK] Toutes checkmarks [OK] vertes
# [OK] Aucun message erreur rouge
# [OK] Bouton [Reboot Now] visible


# PROCESSUS REBOOT:
# ════════════════

# CLIQUER [Reboot Now] -> [Enter]:

# 1. Installer unmount filesystems:
#    • umount /target/boot/efi
#    • umount /target
#    • umount /cdrom

# 2. Sync disques (flush cache):
#    • sync
#    • Garantit toutes écritures sur disque

# 3. VMware eject ISO:
#    • VM détecte CD/DVD plus nécessaire
#    • Éjecte ubuntu-24.04-live-server-amd64.iso
#    • Next boot: Disque en priorité (pas ISO)

# 4. Système reboot:
#    • systemctl reboot
#    • VM restart complet


# PREMIER BOOT APRÈS INSTALLATION:
# ════════════════════════════════

# PHASE 1: BIOS BOOT (3-5 secondes)
# • VM BIOS check hardware
# • Boot order: Disk -> CD-ROM
# • Charge GRUB depuis /dev/sda

# PHASE 2: GRUB MENU (5 secondes timeout)
# ┌────────────────────────────────────────────────┐
# │         GNU GRUB  version 2.12                 │
# │                                                │
# │  *Ubuntu                                       │
# │   Advanced options for Ubuntu                  │
# │   UEFI Firmware Settings                       │
# │                                                │
# │  Use ^ and v to select, Enter to boot         │
# │  Press 'e' to edit, 'c' for command prompt     │
# └────────────────────────────────────────────────┘

# • Sélection automatique "Ubuntu" après 5s
# • Ou [Enter] pour boot immédiat

# PHASE 3: KERNEL LOADING (2-3 secondes)
# Messages défilent:
# Loading Linux 6.8.0-31-generic ...
# Loading initial ramdisk ...

# PHASE 4: BOOT SEQUENCE (10-20 secondes)
# Messages kernel + systemd:
# [  OK  ] Started systemd-networkd.service
# [  OK  ] Started ssh.service
# [  OK  ] Reached target Multi-User System
# [  OK  ] Started Serial Getty on ttyS0

# PHASE 5: LOGIN PROMPT:
# ┌────────────────────────────────────────────────┐
# │                                                │
# │  Ubuntu 24.04 LTS ubuntu-server tty1           │
# │                                                │
# │  ubuntu-server login: _                        │
# │                                                │
# └────────────────────────────────────────────────┘


# PREMIÈRE CONNEXION:
# ══════════════════

# Entrer username (adminuser):
# ubuntu-server login: adminuser

# Entrer password:
# Password: [********** - masqué]

# Message bienvenue (MOTD - Message Of The Day):
# Welcome to Ubuntu 24.04 LTS (GNU/Linux 6.8.0-31-generic x86_64)
# 
#  * Documentation:  https://help.ubuntu.com
#  * Management:     https://landscape.canonical.com
#  * Support:        https://ubuntu.com/pro
# 
# System information as of Sun Dec 15 23:45:12 UTC 2025
# 
#   System load:  0.0              Processes:             92
#   Usage of /:   27.2% of 18.5GB  Users logged in:       0
#   Memory usage: 12%              IPv4 address for ens33: 192.168.120.128
#   Swap usage:   0%
# 
# 0 updates can be applied immediately.
# 
# Last login: Never
# adminuser@ubuntu-server:~$

# PROMPT BASH:
# adminuser@ubuntu-server:~$
# │         │             │└─ Prompt character ($ = user, # = root)
# │         │             └─── Current directory (~ = /home/adminuser)
# │         └─────────────── Hostname
# └───────────────────────── Username


# PREMIÈRES COMMANDES À TESTER:
# ════════════════════════════

# 1. Vérifier utilisateur:
# $ whoami
# adminuser

# $ id
# uid=1000(adminuser) gid=1000(adminuser) groups=1000(adminuser),4(adm),27(sudo),30(dip)

# 2. Tester sudo (droits admin):
# $ sudo ls /root
# [sudo] password for adminuser: [entrer password]
# • Première utilisation sudo: Demande password
# • Timeout: 15 minutes (pas re-demander)
# • sudo = Substitute User DO (exécute commande en root)

# 3. Vérifier réseau:
# $ ip addr show ens33
# 2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500
#     inet 192.168.120.128/24 brd 192.168.120.255 scope global dynamic ens33

# $ ping -c 4 8.8.8.8
# PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
# 64 bytes from 8.8.8.8: icmp_seq=1 ttl=117 time=12.3 ms
# -> Internet fonctionne!

# 4. Vérifier espace disque:
# $ df -h
# Filesystem      Size  Used Avail Use% Mounted on
# /dev/sda2        19G  4.8G   13G  28% /

# 5. Vérifier services actifs:
# $ systemctl status ssh
# [BLACK_CIRCLE] ssh.service - OpenBSD Secure Shell server
#      Loaded: loaded (/lib/systemd/system/ssh.service; enabled)
#      Active: active (running)

# 6. Check kernel version:
# $ uname -r
# 6.8.0-31-generic

# $ uname -a
# Linux ubuntu-server 6.8.0-31-generic #31-Ubuntu SMP x86_64 GNU/Linux

# 7. Lister packages installés:
# $ dpkg -l | wc -l
# 485

# $ apt list --installed | head -5
# adduser/noble,now 3.137ubuntu1 all [installed]
# apt/noble-updates,now 2.7.14build2 amd64 [installed]
# base-files/noble-updates,now 13ubuntu10 amd64 [installed]


# CONNEXION SSH DEPUIS HÔTE:
# ═════════════════════════

# Depuis Windows PowerShell / CMD:
# > ssh adminuser@192.168.120.128
# The authenticity of host '192.168.120.128' can't be established.
# ED25519 key fingerprint is SHA256:abc123xyz789...
# Are you sure you want to continue (yes/no/[fingerprint])? yes
# Warning: Permanently added '192.168.120.128' (ED25519) to known hosts.
# adminuser@192.168.120.128's password: [entrer password]
# Welcome to Ubuntu 24.04 LTS...
# adminuser@ubuntu-server:~$

# FINGERPRINT SSH:
# • Clé publique serveur SSH
# • Unique par installation
# • Stockée client: ~/.ssh/known_hosts (Linux/Mac)
#                   C:\Users\User\.ssh\known_hosts (Windows)
# • Vérifie identité serveur (prévient MITM attacks)
# • Réinstall Ubuntu -> Nouveau fingerprint -> Warning!


# MISE À JOUR SYSTÈME POST-INSTALL:
# ════════════════════════════════

# RECOMMANDÉ: Update immédiat après première connexion

# 1. Update package index:
# $ sudo apt update
# Hit:1 http://archive.ubuntu.com/ubuntu noble InRelease
# Get:2 http://archive.ubuntu.com/ubuntu noble-updates InRelease [126 kB]
# Get:3 http://security.ubuntu.com/ubuntu noble-security InRelease [126 kB]
# Fetched 15.2 MB in 8s (1,891 kB/s)
# Reading package lists... Done
# Building dependency tree... Done
# 42 packages can be upgraded. Run 'apt list --upgradable' to see them.

# 2. Voir packages upgradables:
# $ apt list --upgradable
# base-files/noble-updates 13ubuntu10.1 amd64 [upgradable from: 13ubuntu10]
# curl/noble-updates 8.5.0-2ubuntu10.1 amd64 [upgradable from: 8.5.0-2ubuntu10]
# ...

# 3. Upgrade packages:
# $ sudo apt upgrade
# Reading package lists... Done
# Building dependency tree... Done
# Calculating upgrade... Done
# The following packages will be upgraded:
#   base-files curl libcurl4 openssh-client openssh-server ...
# 42 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
# Need to get 78.5 MB of archives.
# After this operation, 123 kB of additional disk space will be used.
# Do you want to continue? [Y/n] Y

# 4. Reboot si kernel upgrade:
# $ sudo apt list --upgradable | grep linux-image
# linux-image-generic/noble-updates 6.8.0-45.45 amd64 [upgradable from: 6.8.0-31.31]

# Si nouveau kernel installé:
# $ sudo reboot

# 5. Vérifier après reboot:
# $ uname -r
# 6.8.0-45-generic  <- Nouveau kernel


# ÉTAT FINAL SYSTÈME:
# ══════════════════

# [OK] Ubuntu Server 24.04 LTS installé
# [OK] Kernel Linux 6.8+ 
# [OK] Utilisateur adminuser créé (sudo access)
# [OK] Réseau configuré (DHCP ou Static)
# [OK] SSH server actif (port 22)
# [OK] Internet fonctionnel
# [OK] Système à jour
# [OK] ~5GB espace disque utilisé
# [OK] ~400MB RAM utilisée (idle)

# PRÊT POUR:
# • Installation logiciels (web server, database)
# • Configuration services
# • Apprentissage administration Linux
# • Déploiement applications


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 4: INSTALLATION UBUNTU SERVER COMPLÈTE
# ═══════════════════════════════════════════════════════════════════

# RÉCAPITULATIF PARTIE 4:
# ──────────────────────
# [OK] VM démarrée sur ISO Ubuntu Server
# [OK] Langue sélectionnée (English)
# [OK] Clavier configuré (US/FR selon hardware)
# [OK] Type installation choisi (Standard vs Minimized)
# [OK] Réseau configuré (DHCP ou Static IP)
# [OK] Proxy configuré (si requis)
# [OK] Miroir Ubuntu vérifié (archive.ubuntu.com)
# [OK] Stockage partitionné (Entire disk, ext4)
# [OK] Profil utilisateur créé (adminuser)
# [OK] Ubuntu Pro évalué (skipped pour lab)
# [OK] SSH installé (OpenSSH server)
# [OK] Snaps évalués (skipped pour commencer)
# [OK] Installation complétée (10-15 minutes)
# [OK] Système rebooté
# [OK] Premier login réussi
# [OK] Connexion SSH testée
# [OK] Système mis à jour (apt upgrade)

# PROCHAINES PARTIES:
# • Partie 5: Configuration réseau avancée
# • Partie 6: Snapshots et clonage VM
# • Partie 7: Installation VMware Tools
# • Partie 8: Gestion multi-VMs
# • Partie 9+: ESXi, vCenter, Storage, HA...


# ═══════════════════════════════════════════════════════════════════
# À SUIVRE: PARTIE 5 - CONFIGURATION RÉSEAU AVANCÉE
# ═══════════════════════════════════════════════════════════════════



# ═══════════════════════════════════════════════════════════════════
# PARTIE 5: CONFIGURATION RÉSEAU AVANCÉE
# ═══════════════════════════════════════════════════════════════════

# Dans cette partie, on explore en profondeur:
# • Types de réseaux VMware (NAT, Bridged, Host-Only)
# • Configuration IP statique post-installation
# • Netplan configuration avancée
# • Multiple network adapters
# • Port forwarding et firewall
# • Troubleshooting réseau


# ═══════════════════════════════════════════════════════════════════
# 5.1 - TYPES DE RÉSEAUX VMWARE (DÉTAIL COMPLET)
# ═══════════════════════════════════════════════════════════════════

# POURQUOI différents types réseau?
# • Chaque type = Use case spécifique
# • Isolation vs Accessibilité (trade-off sécurité/facilité)
# • NAT: VM accède Internet mais invisible réseau
# • Bridged: VM = PC physique sur LAN
# • Host-Only: VM communiquent entre elles, pas Internet

# VMWARE NETWORK TYPES:
# ═══════════════════════

# 1. NAT (Network Address Translation)
# 2. Bridged (Network Bridge)
# 3. Host-Only (Private Network)
# 4. Custom (VMnet personnalisé)


# ─────────────────────────────────────────────────────────────────
# TYPE 1: NAT (NETWORK ADDRESS TRANSLATION)
# ─────────────────────────────────────────────────────────────────

# ARCHITECTURE NAT:
# ═══════════════

# ┌─────────────────────────── HÔTE WINDOWS/LINUX ──────────────────┐
# │                                                                  │
# │  ┌──── VM Ubuntu ────┐                                          │
# │  │ IP: 192.168.120.128 │                                        │
# │  │ GW: 192.168.120.2   │                                        │
# │  └─────────┬───────────┘                                        │
# │            │                                                     │
# │            │ VMnet8 (Virtual Switch)                            │
# │            v                                                     │
# │  ┌──────────────────┐                                           │
# │  │ VMware NAT Service│                                          │
# │  │ 192.168.120.2     │ <- Gateway/DNS                            │
# │  │ DHCP: 120.128-254 │                                          │
# │  └─────────┬─────────┘                                          │
# │            │ Translate IPs                                      │
# │            │ VM: 192.168.120.128 -> Hôte IP publique             │
# │            v                                                     │
# │  ┌─────────────────────┐                                        │
# │  │ NIC Physique Hôte   │                                        │
# │  │ 192.168.1.100 (LAN) │                                        │
# │  │ ou DHCP ISP         │                                        │
# │  └──────────┬──────────┘                                        │
# │             │                                                    │
# └─────────────┼────────────────────────────────────────────────────┘
#               │
#               v
#         INTERNET / ROUTER LAN
#         ├─ 192.168.1.1 (Home Router)
#         └─ 8.8.8.8 (Google DNS)

# FONCTIONNEMENT NAT:
# ══════════════════

# VM veut accéder google.com:
# 1. VM: curl http://google.com
#    Source: 192.168.120.128:45678
#    Dest: 142.250.185.46:80 (Google)

# 2. Packet arrive VMware NAT service:
#    NAT table entry créée:
#    VM IP:Port          ->  Hôte IP:Port
#    192.168.120.128:45678 -> 192.168.1.100:54321

# 3. NAT service rewrite packet:
#    Source: 192.168.1.100:54321 (IP hôte!)
#    Dest: 142.250.185.46:80
#    -> Envoyé via NIC physique hôte

# 4. Réponse Google:
#    Source: 142.250.185.46:80
#    Dest: 192.168.1.100:54321

# 5. NAT service lookup table:
#    192.168.1.100:54321 -> 192.168.120.128:45678
#    Rewrite:
#    Source: 142.250.185.46:80
#    Dest: 192.168.120.128:45678
#    -> Forward à VM

# 6. VM reçoit réponse:
#    [OK] Connexion établie!
#    [OK] Google ne voit jamais IP VM (192.168.120.128)
#    [OK] Google voit seulement IP hôte (192.168.1.100)

# SUBNET NAT DEFAULT:
# ═════════════════

# VMnet8 (NAT):
# Network: 192.168.120.0/24
# Subnet mask: 255.255.255.0
# Gateway: 192.168.120.2 (VMware NAT service)
# DNS: 192.168.120.2 (forward vers DNS hôte)
# DHCP range: 192.168.120.128 - 192.168.120.254
# Reserved: 192.168.120.1-127 (static IPs possibles)

# FICHIERS CONFIGURATION NAT:
# Windows:
# C:\ProgramData\VMware\vmnetnat.conf
# C:\ProgramData\VMware\vmnetdhcp.conf

# Linux:
# /etc/vmware/vmnet8/nat/nat.conf
# /etc/vmware/vmnet8/dhcpd/dhcpd.conf

# AVANTAGES NAT:
# [OK] VM accède Internet sans config complexe
# [OK] VM invisible depuis LAN (sécurité)
# [OK] Pas besoin IP publique supplémentaire
# [OK] Portable: Fonctionne WiFi, Ethernet, VPN
# [OK] Multiple VMs partagent IP hôte (économie IPs)
# [OK] Isolation: VMs NAT pas accessibles LAN direct

# INCONVÉNIENTS NAT:
# [X] VM pas accessible depuis LAN (sans port forwarding)
# [X] Services VM pas exposables facilement
# [X] Overhead NAT translation (~1-2% latence)
# [X] Certains protocoles problématiques (FTP active, SIP)
# [X] Pas de communication VM-to-VM entre différents hôtes

# USE CASES NAT:
# • Développement local (web dev, testing)
# • Lab isolation (malware analysis, pentesting)
# • Laptop mobile (WiFi café, avion)
# • VMs clientes (pas de services à exposer)
# • Formation/learning


# ─────────────────────────────────────────────────────────────────
# TYPE 2: BRIDGED (NETWORK BRIDGE)
# ─────────────────────────────────────────────────────────────────

# ARCHITECTURE BRIDGED:
# ═══════════════════

# ┌───────────── HÔTE WINDOWS/LINUX ─────────────┐
# │                                              │
# │  ┌──── VM Ubuntu ────┐                       │
# │  │ IP: 192.168.1.150  │ <- DHCP du router LAN │
# │  │ GW: 192.168.1.1    │                      │
# │  └─────────┬──────────┘                      │
# │            │                                  │
# │            │ VMnet0 (Bridge)                  │
# │            v                                  │
# │  ┌─────────────────────┐                     │
# │  │ VMware Bridge       │                     │
# │  │ (Transparent L2)    │                     │
# │  └─────────┬───────────┘                     │
# │            │                                  │
# │            v                                  │
# │  ┌─────────────────────┐                     │
# │  │ NIC Physique Hôte   │                     │
# │  │ 192.168.1.100       │                     │
# │  └──────────┬──────────┘                     │
# │             │                                 │
# └─────────────┼─────────────────────────────────┘
#               │
#               │ Ethernet/WiFi
#               v
#         ┌──────────────────┐
#         │  Switch LAN      │
#         │  192.168.1.0/24  │
#         └─────┬────────────┘
#               ├─ Router: 192.168.1.1
#               ├─ Hôte: 192.168.1.100
#               ├─ VM: 192.168.1.150 <- Visible comme PC physique!
#               ├─ PC Bureau: 192.168.1.101
#               └─ Imprimante: 192.168.1.102

# FONCTIONNEMENT BRIDGED:
# ══════════════════════

# • VMware Bridge = Virtual Ethernet switch
# • VM NIC connectée directement au switch physique
# • VM reçoit IP du même subnet que hôte
# • VM = Peer sur LAN (comme PC physique)
# • MAC address unique pour VM NIC

# VM communique avec PC LAN:
# 1. VM: ping 192.168.1.101 (PC Bureau)
# 2. Packet traverse VMware Bridge
# 3. NIC physique hôte forward frame Ethernet
# 4. Switch LAN route vers 192.168.1.101
# 5. PC Bureau répond directement à VM
# -> Aucune translation! Communication directe.

# DHCP EN BRIDGED:
# ═══════════════

# VM utilise DHCP router LAN:
# • VM envoie DHCP Discover (broadcast)
# • Bridge forward à LAN
# • Router LAN répond DHCP Offer
# • VM reçoit:
#   - IP: 192.168.1.150
#   - Gateway: 192.168.1.1 (router)
#   - DNS: 192.168.1.1 ou 8.8.8.8
#   - Subnet: 255.255.255.0

# CONFIGURATION BRIDGED INTERFACE:
# Settings VM -> Network Adapter -> Bridged
# • Bridged to: Auto-detect
#   Ou spécifique: Ethernet0, WiFi Adapter, etc.
# • Replicate physical network connection state
#   (déconnecte VM NIC si hôte NIC down)

# AVANTAGES BRIDGED:
# [OK] VM = PC physique (full network citizen)
# [OK] Accessible depuis LAN (SSH, HTTP, etc.)
# [OK] Services exposables facilement
# [OK] Pas overhead NAT (performance max)
# [OK] Tous protocoles fonctionnent (FTP, SIP, VoIP)
# [OK] VM-to-VM communication sans config

# INCONVÉNIENTS BRIDGED:
# [X] VM visible sur LAN (sécurité risque)
# [X] Consomme IP du pool DHCP router
# [X] Problématique WiFi publics (hotspots bloquent)
# [X] VPN hôte: VM pas dans VPN tunnel
# [X] Mobile: IP change avec réseau

# USE CASES BRIDGED:
# • Serveurs LAN (web server, NAS)
# • VMs accessibles depuis autres PCs
# • Testing réseau réel
# • Simulations infrastructure
# • Development servers équipe
# • Remplacer PC physique


# ─────────────────────────────────────────────────────────────────
# TYPE 3: HOST-ONLY (PRIVATE NETWORK)
# ─────────────────────────────────────────────────────────────────

# ARCHITECTURE HOST-ONLY:
# ═══════════════════════

# ┌───────────── HÔTE WINDOWS/LINUX ─────────────┐
# │                                              │
# │  ┌──── VM Ubuntu 1 ─┐   ┌─ VM Ubuntu 2 ───┐ │
# │  │ IP: 192.168.80.128│   │ 192.168.80.129  │ │
# │  │ GW: 192.168.80.2  │   │ GW: 192.168.80.2│ │
# │  └─────────┬─────────┘   └────┬────────────┘ │
# │            │                  │               │
# │            └──────┬───────────┘               │
# │                   │ VMnet1 (Host-Only)        │
# │                   v                           │
# │  ┌────────────────────────────────┐          │
# │  │ VMware Host-Only Adapter       │          │
# │  │ IP: 192.168.80.1 (hôte)        │          │
# │  │ DHCP: 192.168.80.128-254       │          │
# │  └────────────────────────────────┘          │
# │                                              │
# │  ┌─────────────────────┐                     │
# │  │ NIC Physique Hôte   │                     │
# │  │ 192.168.1.100       │ <- ISOLÉ!            │
# │  └──────────┬──────────┘                     │
# │             │                                 │
# └─────────────┼─────────────────────────────────┘
#               │
#               v
#         INTERNET / LAN
#         (PAS d'accès depuis Host-Only VMs!)

# FONCTIONNEMENT HOST-ONLY:
# ═════════════════════════

# • Réseau privé complètement isolé
# • VMs communiquent entre elles
# • Hôte communique avec VMs
# • AUCUNE connexion Internet
# • AUCUNE connexion LAN
# • Comme un switch réseau déconnecté

# Communication VM1 -> VM2:
# 1. VM1: ping 192.168.80.129
# 2. Packet va à VMnet1 (virtual switch)
# 3. VMnet1 forward à VM2
# 4. VM2 répond
# -> Communication OK!

# Communication VM -> Internet:
# 1. VM: ping 8.8.8.8
# 2. Packet va à gateway 192.168.80.2
# 3. DROPPED! (pas de routing vers Internet)
# -> Timeout

# Communication Hôte -> VM:
# 1. Hôte: ssh adminuser@192.168.80.128
# 2. Packet via VMware Host-Only adapter
# 3. VMnet1 forward à VM
# 4. SSH connexion établie
# -> Hôte peut gérer VMs!

# SUBNET HOST-ONLY DEFAULT:
# ════════════════════════

# VMnet1 (Host-Only):
# Network: 192.168.80.0/24
# Subnet mask: 255.255.255.0
# Gateway: 192.168.80.2 (virtuel, pas de routing)
# DHCP range: 192.168.80.128 - 192.168.80.254
# Host adapter: 192.168.80.1

# FICHIERS CONFIGURATION:
# Windows:
# C:\ProgramData\VMware\vmnetdhcp.conf (VMnet1)

# Linux:
# /etc/vmware/vmnet1/dhcpd/dhcpd.conf

# AVANTAGES HOST-ONLY:
# [OK] Isolation totale (sécurité max)
# [OK] Lab testing malware (pas de propagation)
# [OK] Réseau privé multi-VMs
# [OK] Pas de conflits IP avec LAN
# [OK] Répétable (même config partout)
# [OK] Hôte accède VMs (management facile)

# INCONVÉNIENTS HOST-ONLY:
# [X] PAS D'INTERNET (unless routing manuel)
# [X] VMs isolées du LAN
# [X] Pas download packages (sauf via hôte proxy)
# [X] Complexe si besoin Internet occasionnel

# USE CASES HOST-ONLY:
# • Lab isolated networks (Kubernetes cluster)
# • Malware analysis (sandbox sécurisé)
# • Network simulations (routers, firewalls)
# • Development multi-tier (web + db isolés)
# • Training environments (pas besoin Internet)
# • Security testing (pentesting isolé)


# ─────────────────────────────────────────────────────────────────
# TYPE 4: CUSTOM NETWORKS (VMnet2-VMnet19)
# ─────────────────────────────────────────────────────────────────

# POURQUOI Custom VMnet?
# • Créer multiples réseaux isolés
# • Chaque VMnet = Réseau virtuel séparé
# • Simulation infrastructure complexe
# • Segmentation réseau (DMZ, Internal, Management)

# EXEMPLE ARCHITECTURE MULTI-VMnet:
# ═════════════════════════════════

# ┌────────────────── HÔTE ──────────────────────┐
# │                                              │
# │  VMnet2 (DMZ - 10.0.1.0/24)                  │
# │  ├─ Web Server VM: 10.0.1.10                 │
# │  └─ Mail Server VM: 10.0.1.20                │
# │                                              │
# │  VMnet3 (Internal - 10.0.2.0/24)             │
# │  ├─ Database VM: 10.0.2.10                   │
# │  ├─ App Server VM: 10.0.2.20                 │
# │  └─ File Server VM: 10.0.2.30                │
# │                                              │
# │  VMnet4 (Management - 10.0.3.0/24)           │
# │  ├─ Monitoring VM: 10.0.3.10                 │
# │  └─ Backup VM: 10.0.3.20                     │
# │                                              │
# │  VMnet8 (NAT - 192.168.120.0/24)             │
# │  └─ Router VM (multi-NIC):                   │
# │      ens33: 10.0.1.1 (DMZ)                   │
# │      ens34: 10.0.2.1 (Internal)              │
# │      ens35: 10.0.3.1 (Management)            │
# │      ens36: 192.168.120.100 (NAT Internet)   │
# │                                              │
# └──────────────────────────────────────────────┘

# CONFIGURATION CUSTOM VMNET:
# ═══════════════════════════

# Windows:
# Edit -> Virtual Network Editor -> [Administrator]
# 1. [Add Network...] -> Sélectionner VMnet2
# 2. Type: Host-Only ou NAT
# 3. Subnet IP: 10.0.1.0
# 4. Subnet mask: 255.255.255.0
# 5. Use local DHCP: [x] (optionnel)
# 6. [OK]

# Linux:
# /etc/vmware/networking (config file)
# answer VNET_2_VIRTUAL_ADAPTER yes
# answer VNET_2_HOSTONLY_NETMASK 255.255.255.0
# answer VNET_2_HOSTONLY_SUBNET 10.0.1.0

# VM ASSIGNMENT:
# VM Settings -> Network Adapter -> Custom -> VMnet2

# ROUTING ENTRE VMnets:
# ════════════════════

# Par défaut: VMnets isolés (pas de routing)
# Pour interconnecter: VM Router avec multiple NICs

# VM Router (pfSense, VyOS, Ubuntu):
# • NIC1 (ens33): VMnet2 -> 10.0.1.1/24
# • NIC2 (ens34): VMnet3 -> 10.0.2.1/24
# • NIC3 (ens35): VMnet8 -> 192.168.120.100/24

# Enable IP forwarding:
# $ sudo sysctl -w net.ipv4.ip_forward=1
# $ sudo iptables -t nat -A POSTROUTING -o ens35 -j MASQUERADE

# VMs VMnet2 route via 10.0.1.1:
# $ sudo ip route add default via 10.0.1.1

# -> VMnet2 peut accéder Internet via Router VM!


# COMPARAISON TYPES RÉSEAU:
# ═════════════════════════

# ╔═══════════════╦═════════╦═════════╦═══════════╦═══════════╗
# ║ Feature       ║ NAT     ║ Bridged ║ Host-Only ║ Custom    ║
# ╠═══════════════╬═════════╬═════════╬═══════════╬═══════════╣
# ║ Internet      ║ Yes     ║ Yes     ║ No        ║ Configur. ║
# ║ LAN Access    ║ No      ║ Yes     ║ No        ║ No        ║
# ║ Host->VM       ║ NAT+PF  ║ Yes     ║ Yes       ║ Yes       ║
# ║ VM->VM         ║ Same    ║ All     ║ Same      ║ Same      ║
# ║ VM Visible    ║ No      ║ Yes     ║ No        ║ No        ║
# ║ IP Source     ║ DHCP VM ║ DHCP LAN║ DHCP VM   ║ DHCP VM   ║
# ║ Portable      ║ Yes     ║ Limited ║ Yes       ║ Yes       ║
# ║ Isolation     ║ Medium  ║ Low     ║ High      ║ High      ║
# ║ Complexity    ║ Low     ║ Low     ║ Low       ║ Medium    ║
# ║ Use Case      ║ Dev/Lab ║ Servers ║ Testing   ║ Advanced  ║
# ╚═══════════════╩═════════╩═════════╩═══════════╩═══════════╝

# RECOMMANDATION PAR SCÉNARIO:
# ═══════════════════════════

# Scénario 1: Learning Linux (débutant)
# -> NAT (simple, Internet fonctionne, isolé)

# Scénario 2: Web server accessible LAN
# -> Bridged (VM visible réseau, services exposés)

# Scénario 3: Cluster Kubernetes multi-VMs
# -> Host-Only (VMs communiquent, isolées Internet)

# Scénario 4: Simulation datacenter (DMZ + Internal)
# -> Custom VMnets multiples (segmentation réseau)

# Scénario 5: Malware analysis
# -> Host-Only (isolation totale, pas propagation)

# Scénario 6: Development team (partage VM)
# -> Bridged (équipe accède VM, pas NAT+PF complexe)


# ═══════════════════════════════════════════════════════════════════
# 5.2 - CONFIGURATION IP STATIQUE POST-INSTALLATION
# ═══════════════════════════════════════════════════════════════════

# POURQUOI IP statique?
# • Services: Web server, Database -> IP fixe requise
# • DNS: Records pointent IP spécifique
# • SSH: Connexion sans chercher nouvelle IP
# • Automation: Scripts utilisent IP connue
# • Firewall rules: Basées sur IPs

# QUAND utiliser IP statique?
# [OK] Serveurs production
# [OK] Services réseau (DNS, DHCP, Web)
# [OK] Lab environments (testing répétable)
# [OK] VMs long-term (pas recréées souvent)
# [X] VMs temporaires/testing
# [X] Laptops mobiles (DHCP meilleur)

# UBUNTU NETWORKING:
# ═════════════════

# Ubuntu 18.04+: Netplan (config YAML)
# • Remplace: /etc/network/interfaces (deprecated)
# • Backend: systemd-networkd ou NetworkManager
# • Config: /etc/netplan/*.yaml


# ─────────────────────────────────────────────────────────────────
# MÉTHODE 1: CONFIGURATION VIA NETPLAN (RECOMMANDÉE)
# ─────────────────────────────────────────────────────────────────

# ÉTAPE 1: Vérifier configuration actuelle
# ════════════════════════════════════════

# Connexion SSH à VM:
# $ ssh adminuser@192.168.120.128

# Afficher interfaces réseau:
# $ ip addr show
# 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536
#     inet 127.0.0.1/8 scope host lo
# 2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500
#     inet 192.168.120.128/24 brd 192.168.120.255 scope global dynamic ens33

# Afficher routes:
# $ ip route show
# default via 192.168.120.2 dev ens33 proto dhcp src 192.168.120.128 metric 100
# 192.168.120.0/24 dev ens33 proto kernel scope link src 192.168.120.128

# Afficher DNS:
# $ resolvectl status
# Global:
#   DNS Servers: 192.168.120.2
# Link 2 (ens33):
#   Current DNS Server: 192.168.120.2


# ÉTAPE 2: Lister fichiers Netplan existants
# ═══════════════════════════════════════════

# $ ls -la /etc/netplan/
# total 12
# drwxr-xr-x  2 root root 4096 Dec 15 20:45 .
# drwxr-xr-x 95 root root 4096 Dec 15 20:50 ..
# -rw-r--r--  1 root root  116 Dec 15 20:45 00-installer-config.yaml

# Lire config actuelle:
# $ cat /etc/netplan/00-installer-config.yaml
# network:
#   version: 2
#   ethernets:
#     ens33:
#       dhcp4: true

# STRUCTURE FICHIER NETPLAN:
# network:
#   version: 2                    <- Version Netplan (always 2)
#   renderer: networkd            <- Backend (networkd ou NetworkManager)
#   ethernets:                    <- Interfaces Ethernet
#     INTERFACE_NAME:             <- ex: ens33, eth0, enp0s3
#       dhcp4: true/false         <- IPv4 DHCP
#       dhcp6: true/false         <- IPv6 DHCP
#       addresses:                <- IPs statiques
#         - IP/MASK               <- ex: 192.168.120.100/24
#       gateway4: IP              <- (deprecated) utiliser routes:
#       routes:                   <- Routes statiques
#         - to: default           <- Default route
#           via: GATEWAY_IP       <- ex: 192.168.120.2
#       nameservers:              <- DNS servers
#         addresses:              <- Liste DNS
#           - DNS1                <- ex: 8.8.8.8
#           - DNS2                <- ex: 8.8.4.4


# ÉTAPE 3: Backup config actuelle
# ═══════════════════════════════

# TOUJOURS backup avant modification:
# $ sudo cp /etc/netplan/00-installer-config.yaml \
#            /etc/netplan/00-installer-config.yaml.backup

# Vérifier backup créé:
# $ ls -la /etc/netplan/
# -rw-r--r-- 1 root root 116 Dec 15 20:45 00-installer-config.yaml
# -rw-r--r-- 1 root root 116 Dec 15 21:00 00-installer-config.yaml.backup


# ÉTAPE 4: Éditer configuration Netplan
# ═══════════════════════════════════════

# Éditer avec nano (ou vim):
# $ sudo nano /etc/netplan/00-installer-config.yaml

# AVANT (DHCP):
# network:
#   version: 2
#   ethernets:
#     ens33:
#       dhcp4: true

# APRÈS (IP STATIQUE):
# network:
#   version: 2
#   ethernets:
#     ens33:
#       dhcp4: false
#       addresses:
#         - 192.168.120.100/24
#       routes:
#         - to: default
#           via: 192.168.120.2
#       nameservers:
#         addresses:
#           - 8.8.8.8
#           - 8.8.4.4

# ATTENTION YAML:
# • Indentation STRICTE (2 espaces, PAS de tabs!)
# • Tirets alignés
# • Pas de trailing whitespace
# • YAML = Yet Another Markup Language (très strict syntaxe)

# ERREUR COMMUNE:
# [X] Utiliser tabs au lieu espaces -> Erreur parsing
# [X] Mauvaise indentation -> Config ignorée
# [X] Oublier tiret dans addresses: -> Erreur
# [OK] Copier-coller exact du template ci-dessus

# Sauvegarder fichier:
# Ctrl+O -> Enter -> Ctrl+X


# ÉTAPE 5: Valider syntaxe Netplan
# ════════════════════════════════

# Tester config AVANT appliquer:
# $ sudo netplan try
# Do you want to keep these settings?
# 
# Press ENTER before the timeout to accept the new configuration
# 
# Changes will revert in 120 seconds

# SI CONFIG OK:
# • Network fonctionne -> Appuyer [Enter] dans 120s
# • Settings sauvegardées

# SI CONFIG ERREUR:
# • Network down -> Attendre 120s
# • Netplan revert automatiquement config précédente
# • Connexion SSH restaurée
# • Re-éditer fichier et corriger erreur

# EXEMPLE ERREUR SYNTAXE:
# $ sudo netplan try
# Error in network definition: expected mapping (check indentation)
# -> Vérifier indentation YAML

# SÉCURITÉ:
# netplan try = Safety net (évite lockout SSH)
# • Timeout 120s = Temps corriger via console si erreur
# • Si timeout expire -> Revert config
# • Si [Enter] pressé -> Commit config


# ÉTAPE 6: Appliquer configuration
# ════════════════════════════════

# SI netplan try OK -> Appliquer définitivement:
# $ sudo netplan apply

# Ou directement (sans safety net, risqué):
# $ sudo netplan apply
# • Applique config immédiatement
# • Pas de rollback automatique
# • Risque: Lockout SSH si erreur

# CE QUI SE PASSE:
# • systemd-networkd restart
# • Interface ens33 reconfigurée
# • Ancienne IP 192.168.120.128 libérée
# • Nouvelle IP 192.168.120.100 assignée
# • Routes updated
# • DNS updated


# ÉTAPE 7: Vérifier nouvelle configuration
# ═════════════════════════════════════════

# Vérifier IP statique assignée:
# $ ip addr show ens33
# 2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500
#     link/ether 00:0c:29:3f:5e:12 brd ff:ff:ff:ff:ff:ff
#     inet 192.168.120.100/24 brd 192.168.120.255 scope global ens33
#     ^                     ^
#     └─ IP statique        └─ Pas "dynamic" (était DHCP avant)

# Vérifier gateway:
# $ ip route show
# default via 192.168.120.2 dev ens33 proto static
# 192.168.120.0/24 dev ens33 proto kernel scope link src 192.168.120.100

# Vérifier DNS:
# $ resolvectl status | grep "DNS Servers"
# DNS Servers: 8.8.8.8
#              8.8.4.4

# Ou:
# $ cat /etc/resolv.conf
# nameserver 127.0.0.53  <- systemd-resolved stub
# • systemd-resolved écoute 127.0.0.53
# • Forward vers 8.8.8.8, 8.8.4.4 (config Netplan)

# Tester connectivité:
# $ ping -c 4 8.8.8.8
# PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
# 64 bytes from 8.8.8.8: icmp_seq=1 ttl=117 time=12.3 ms
# -> Internet fonctionne!

# $ ping -c 4 google.com
# PING google.com (142.250.185.46) 56(84) bytes of data.
# 64 bytes from lhr25s34-in-f14.1e100.net (142.250.185.46): icmp_seq=1 ttl=117
# -> DNS résolution fonctionne!


# ÉTAPE 8: Reconnexion SSH nouvelle IP
# ═════════════════════════════════════

# Déconnecter session SSH actuelle:
# $ exit

# Reconnexion avec nouvelle IP statique:
# > ssh adminuser@192.168.120.100
# adminuser@192.168.120.100's password:
# Welcome to Ubuntu 24.04 LTS...
# adminuser@ubuntu-server:~$

# [OK] IP statique fonctionnelle!
# [OK] Connexions futures toujours même IP
# [OK] Plus de recherche IP DHCP


# CONFIGURATION MULTIPLES IPs (OPTIONAL):
# ═══════════════════════════════════════

# VM avec multiple IPs même interface:
# network:
#   version: 2
#   ethernets:
#     ens33:
#       dhcp4: false
#       addresses:
#         - 192.168.120.100/24  <- IP primaire
#         - 192.168.120.101/24  <- IP secondaire
#         - 192.168.120.102/24  <- IP tertiaire
#       routes:
#         - to: default
#           via: 192.168.120.2
#       nameservers:
#         addresses: [8.8.8.8, 8.8.4.4]

# Use case:
# • Multiple web servers (vhosts)
# • Failover IPs
# • Testing load balancing


# TROUBLESHOOTING NETPLAN:
# ═══════════════════════

# Erreur: "No route to host" après apply
# Cause: Gateway incorrect ou inaccessible
# Solution: Vérifier gateway ping-able:
# $ ping 192.168.120.2
# Si timeout -> Vérifier VMware NAT service actif

# Erreur: "Temporary failure in name resolution"
# Cause: DNS servers incorrects ou inaccessibles
# Solution: Tester DNS:
# $ dig @8.8.8.8 google.com
# $ nslookup google.com 8.8.8.8
# Si timeout -> Vérifier firewall/NAT

# Erreur: "Network is unreachable"
# Cause: Pas de default route
# Solution: Ajouter dans routes:
#   - to: default
#     via: 192.168.120.2

# Erreur: Config ignored silencieusement
# Cause: Indentation YAML incorrecte
# Solution: Valider YAML:
# $ sudo netplan --debug generate
# $ sudo netplan --debug apply

# Rollback config:
# $ sudo cp /etc/netplan/00-installer-config.yaml.backup \
#            /etc/netplan/00-installer-config.yaml
# $ sudo netplan apply


# ═══════════════════════════════════════════════════════════════════
# 5.3 - MULTIPLE NETWORK ADAPTERS
# ═══════════════════════════════════════════════════════════════════

# POURQUOI multiple NICs?
# • Segmentation réseau (DMZ + Internal)
# • High availability (NIC bonding)
# • Traffic separation (Management + Data)
# • Router/Firewall VMs (multiple networks)
# • Performance (aggregate bandwidth)

# USE CASES:
# ═════════

# Scénario 1: Router VM
# • NIC1 (ens33): NAT -> Internet
# • NIC2 (ens34): Host-Only -> Internal network
# • Forward traffic entre réseaux

# Scénario 2: Web Server multi-homed
# • NIC1 (ens33): DMZ -> Public web traffic
# • NIC2 (ens34): Internal -> Database access

# Scénario 3: NIC Bonding (HA)
# • NIC1 + NIC2: Bonded (failover ou load-balance)
# • Si NIC1 down -> NIC2 prend relève


# AJOUTER NETWORK ADAPTER À VM:
# ════════════════════════════

# VM éteinte (powered off):
# 1. VM Settings -> [Add...] -> Hardware: Network Adapter -> [Finish]
# 2. Nouveau adapter apparaît:
#    Network Adapter (ens33) <- Existant
#    Network Adapter 2 (ens34) <- Nouveau

# 3. Configurer nouveau adapter:
#    Network connection:
#    • NAT / Bridged / Host-Only / Custom
#    Exemple: Custom VMnet2 (Internal network)

# 4. [OK] -> Démarrer VM

# VM allumée (hot-add si VMware Tools installé):
# • Possible ajouter NIC à chaud
# • VM détecte nouveau hardware automatiquement
# • Interface apparaît: ens34


# VÉRIFIER INTERFACES DÉTECTÉES:
# ══════════════════════════════

# $ ip link show
# 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536
# 2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500
# 3: ens34: <BROADCAST,MULTICAST> mtu 1500  <- Nouveau (DOWN)

# ens34 = DOWN (pas configuré encore)


# CONFIGURATION MULTIPLE NICS NETPLAN:
# ═══════════════════════════════════

# $ sudo nano /etc/netplan/00-installer-config.yaml

# network:
#   version: 2
#   ethernets:
#     ens33:
#       dhcp4: false
#       addresses: [192.168.120.100/24]
#       routes:
#         - to: default
#           via: 192.168.120.2
#       nameservers:
#         addresses: [8.8.8.8]
#     
#     ens34:
#       dhcp4: false
#       addresses: [10.0.1.10/24]
#       # Pas de default route ici (déjà sur ens33)

# Appliquer:
# $ sudo netplan apply

# Vérifier:
# $ ip addr show ens34
# 3: ens34: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500
#     inet 10.0.1.10/24 brd 10.0.1.255 scope global ens34


# ROUTING TABLE AVEC MULTIPLE NICS:
# ═════════════════════════════════

# $ ip route show
# default via 192.168.120.2 dev ens33 proto static   <- Default Internet
# 10.0.1.0/24 dev ens34 proto kernel scope link src 10.0.1.10  <- Local subnet
# 192.168.120.0/24 dev ens33 proto kernel scope link src 192.168.120.100

# Traffic routing:
# • Destination 10.0.1.x -> ens34 (direct)
# • Destination 192.168.120.x -> ens33 (direct)
# • Autre (Internet) -> default via ens33


# POLICY-BASED ROUTING (AVANCÉ):
# ══════════════════════════════

# Router traffic selon source IP:
# network:
#   version: 2
#   ethernets:
#     ens33:
#       addresses: [192.168.120.100/24]
#       routes:
#         - to: default
#           via: 192.168.120.2
#           table: 100  <- Route table custom
#       routing-policy:
#         - from: 192.168.120.100
#           table: 100
#     
#     ens34:
#       addresses: [10.0.1.10/24]
#       routes:
#         - to: default
#           via: 10.0.1.1
#           table: 200
#       routing-policy:
#         - from: 10.0.1.10
#           table: 200

# Use case:
# • Traffic source 192.168.120.100 -> Route via ens33
# • Traffic source 10.0.1.10 -> Route via ens34


# NIC BONDING (LINK AGGREGATION):
# ═══════════════════════════════

# Modes bonding:
# • mode 0 (balance-rr): Round-robin (load balance)
# • mode 1 (active-backup): Failover (HA)
# • mode 2 (balance-xor): XOR hash (load balance)
# • mode 4 (802.3ad): LACP (switch support requis)
# • mode 5 (balance-tlb): Transmit load balance
# • mode 6 (balance-alb): Adaptive load balance

# Configuration Netplan:
# network:
#   version: 2
#   ethernets:
#     ens33:
#       dhcp4: false
#     ens34:
#       dhcp4: false
#   bonds:
#     bond0:
#       interfaces: [ens33, ens34]
#       addresses: [192.168.120.100/24]
#       parameters:
#         mode: active-backup  <- Failover HA
#         primary: ens33       <- Primary NIC
#         mii-monitor-interval: 100
#       routes:
#         - to: default
#           via: 192.168.120.2

# Vérifier bond:
# $ cat /proc/net/bonding/bond0
# Bonding Mode: fault-tolerance (active-backup)
# Primary Slave: ens33 (primary_reselect always)
# Currently Active Slave: ens33
# MII Status: up
# MII Polling Interval (ms): 100

# Test failover:
# $ sudo ip link set ens33 down
# -> bond0 switch automatiquement vers ens34


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 5: CONFIGURATION RÉSEAU AVANCÉE
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# PARTIE 6: SNAPSHOTS ET GESTION DES ÉTATS VM
# ═══════════════════════════════════════════════════════════════════


# ═══ 6.1 COMPRENDRE LES SNAPSHOTS ═══

# POURQUOI les snapshots existent?
# ════════════════════════════════

# PROBLÈME: Modifications risquées
# ────────────────────────────────

# Scénarios dangereux:
# • Installation nouveau logiciel inconnu
# • Mise à jour système critique (kernel Linux)
# • Configuration complexe (firewall, réseau)
# • Test script destructif
# • Modification base données production
# • Patch sécurité non testé

# Sans snapshot:
# [X] Modification casse système -> Réinstallation complète (4 heures)
# [X] Config réseau erreur -> VM inaccessible, debug difficile
# [X] Update cassé -> Rollback manuel impossible
# [X] Test destructif -> Perte données définitive

# Exemple catastrophe réelle:
# Administrateur: $ sudo apt upgrade
# -> Kernel panic après reboot
# -> VM ne boot plus
# -> Pas de backup récent
# -> Réinstallation Ubuntu = 6 heures travail perdu


# SOLUTION: Snapshots VMware
# ══════════════════════════

# Snapshot = Photo instantanée état VM

# AVANT modification dangereuse:
# 1. Créer snapshot (30 secondes)
# 2. Effectuer modification
# 3. SI succès -> Supprimer snapshot
# 4. SI échec -> Revert to snapshot (2 minutes)
# -> VM retourne état EXACT avant modif!

# AVANTAGES:
# [OK] Retour arrière instantané
# [OK] Zéro perte données
# [OK] Test sans risque
# [OK] Multiple points de restauration
# [OK] Capture état complet (disque + RAM + settings)

# Exemple succès:
# Développeur teste script suppression fichiers:
# 1. Snapshot "avant-script-dangereux"
# 2. Execute script -> ERREUR: supprime fichiers système!
# 3. Revert snapshot -> VM restaurée, 0 fichiers perdus
# 4. Correction script, nouveau test
# -> Développement sécurisé!


# ANALOGIE: Points de sauvegarde jeu vidéo
# ═══════════════════════════════════════

# Jeu vidéo RPG:
# • Boss difficile à venir
# • SAVE avant combat
# • Combat -> Mort
# • LOAD sauvegarde -> Retry avec différente stratégie
# • Unlimited attempts sans perdre progression

# Snapshot VM = identique:
# • Modification risquée à venir
# • Snapshot avant modif
# • Modif -> Échec/Crash
# • Revert snapshot -> Retry avec différente approche
# • Unlimited tests sans casser VM


# QU'EST-CE exactement qu'un snapshot?
# ════════════════════════════════════

# Snapshot capture 3 éléments:
# ─────────────────────────────

# 1. ÉTAT DISQUE (Disk state)
#    • Tous fichiers VM (.vmdk)
#    • Système fichiers complet
#    • Applications installées
#    • Données utilisateurs
#    • Configuration OS

# 2. ÉTAT MÉMOIRE (Memory state) [OPTIONAL]
#    • Contenu RAM
#    • Processus en cours
#    • Connexions réseau actives
#    • Applications ouvertes
#    • VM running -> Capture exact comme hibernation PC

# 3. SETTINGS VM (VM settings)
#    • Configuration hardware (vCPU, RAM, NICs)
#    • Devices connectés
#    • Paramètres réseau


# STRUCTURE FICHIERS SNAPSHOT:
# ════════════════════════════

# AVANT snapshot:
# ───────────────
# Ubuntu-Server.vmx          <- Configuration VM
# Ubuntu-Server.vmdk         <- Descriptor disque
# Ubuntu-Server-flat.vmdk    <- Données disque (20GB)
# Ubuntu-Server.nvram        <- BIOS

# APRÈS snapshot "Avant-Update":
# ──────────────────────────────
# Ubuntu-Server.vmx
# Ubuntu-Server.vmdk         <- READ-ONLY maintenant!
# Ubuntu-Server-flat.vmdk    <- READ-ONLY (état snapshot)
# Ubuntu-Server-000001.vmdk  <- Descriptor delta disk
# Ubuntu-Server-000001-delta.vmdk  <- Modifications APRÈS snapshot
# Ubuntu-Server.vmsd         <- Snapshot metadata
# Ubuntu-Server-Snapshot1.vmsn  <- Snapshot state (RAM si capturé)

# APRÈS 2ème snapshot "Après-Config-Réseau":
# ─────────────────────────────────────────
# [fichiers précédents...]
# Ubuntu-Server-000002.vmdk  <- Descriptor 2ème delta
# Ubuntu-Server-000002-delta.vmdk  <- Modifications 2ème snapshot
# Ubuntu-Server-Snapshot2.vmsn  <- 2ème snapshot state

# Chaîne snapshots:
# Disque original (flat.vmdk) [READ-ONLY]
#   v
# Delta-1 (000001-delta.vmdk) <- Snapshot 1
#   v
# Delta-2 (000002-delta.vmdk) <- Snapshot 2 (état actuel VM)


# DELTA DISKS - Concept clé:
# ══════════════════════════

# Delta disk = Fichier contenant SEULEMENT les changements

# Exemple concret:
# ────────────────

# État disque snapshot:
# /home/user/file1.txt = "Hello"  <- Dans flat.vmdk
# /home/user/file2.txt = "World"  <- Dans flat.vmdk
# Total: 20GB utilisé

# Après snapshot, modifications:
# $ echo "Modified" > /home/user/file1.txt  <- Modifié
# $ touch /home/user/file3.txt  <- Nouveau
# [file2.txt non modifié]

# Delta disk contient:
# • file1.txt version modifiée
# • file3.txt nouveau
# • Pointeur vers flat.vmdk pour file2.txt (inchangé)
# Taille delta: 50MB (pas 20GB!)

# Lecture VM:
# • file1.txt -> Lu depuis delta disk (version modifiée)
# • file2.txt -> Lu depuis flat.vmdk (original)
# • file3.txt -> Lu depuis delta disk (nouveau)


# TYPES DE SNAPSHOTS:
# ═══════════════════

# 1. SNAPSHOT WITHOUT MEMORY (Disque seul)
#    ──────────────────────────────────────
#    Capture: État disque uniquement
#    VM doit être: Powered off OU running (mais reboot après revert)
#    Taille: Proportionnelle changements disque
#    Revert: VM démarre boot normal
#    Use case: Backup avant update, test config
#    Vitesse création: Rapide (secondes)

# 2. SNAPSHOT WITH MEMORY (Disque + RAM)
#    ────────────────────────────────────
#    Capture: Disque + RAM + état processus
#    VM doit être: Running (powered on)
#    Taille: Changements disque + taille RAM allouée
#    Revert: VM restaure état EXACT (applications running)
#    Use case: Debug problème, capture state exact
#    Vitesse création: Moyenne (30-60s selon RAM)

# 3. QUIESCED SNAPSHOT (Application-consistent)
#    ──────────────────────────────────────────
#    Capture: Disque avec flush caches + quiesce apps
#    Nécessite: VMware Tools installé
#    Processus: 
#      • VMware Tools signale apps (DB, etc)
#      • Apps flush données vers disque
#      • Filesystem sync
#      • Snapshot créé
#      • Apps reprennent
#    Use case: Backup base données, production systems
#    Garantie: Données cohérentes (pas corruption)


# QUAND utiliser quel type?
# ═════════════════════════

# Snapshot WITHOUT memory:
# [OK] Update système (kernel, packages)
# [OK] Test nouvelle config
# [OK] Backup avant maintenance
# [OK] Template/base system
# [X] Debug problème runtime (apps fermées au revert)

# Snapshot WITH memory:
# [OK] Debug application problématique (garde processes)
# [OK] Capture exact state pour analyse
# [OK] Test destructif avec rollback immediat
# [X] Large RAM (snapshot 64GB RAM = 64GB fichier!)
# [X] Production (impact performance pendant capture)

# Quiesced snapshot:
# [OK] Backup production database
# [OK] VM critique avec transactions actives
# [OK] Environnement avec données importantes
# [X] VM sans VMware Tools
# [X] Applications ne supportant pas quiesce


# LIMITATIONS SNAPSHOTS:
# ═════════════════════

# [ATTENTION] IMPORTANT: Snapshots ≠ Backups!
# ──────────────────────────────────

# Snapshots limitations:
# • Fichiers snapshot sur MÊME stockage que VM
# • Si disque physique meurt -> VM + snapshots perdus!
# • Snapshots dégradent performance (delta chain)
# • Snapshots consomment espace disque rapidement
# • Maximum recommandé: 3-5 snapshots par VM
# • Durée maximale recommandée: 24-72 heures
# • JAMAIS utiliser snapshot long-terme!

# Backup vs Snapshot:
# ───────────────────
# BACKUP:
# • Copie EXTERNE (autre disque/serveur/cloud)
# • Protection crash hardware
# • Retention long-terme (jours/mois/années)
# • 0 impact performance production
# • Use case: Disaster recovery, archives

# SNAPSHOT:
# • Copie INTERNE (même datastore)
# • Protection erreurs configuration
# • Retention court-terme (minutes/heures/jours)
# • Impact performance si chain longue
# • Use case: Test, rollback rapide


# IMPACT PERFORMANCE SNAPSHOTS:
# ═════════════════════════════

# Single snapshot:
# • Impact minimal: 5-10% overhead I/O
# • Lecture: VM lit original OU delta
# • Écriture: Toujours vers delta actuel

# Multiple snapshots (chain):
# • Delta 1 -> Delta 2 -> Delta 3 (actuel)
# • Lecture peut traverser 3 fichiers!
# • Impact: 15-30% overhead I/O
# • Plus chain longue = plus lent

# Exemple concret:
# ────────────────
# VM sans snapshot: 1000 IOPS
# VM avec 1 snapshot: 900-950 IOPS
# VM avec 3 snapshots: 700-850 IOPS
# VM avec 10 snapshots: 400-600 IOPS [ATTENTION] DANGEREUX!

# Best practice:
# • Maximum 2-3 snapshots simultanés
# • Supprimer snapshots après tests
# • Consolider régulièrement


# ═══ 6.2 CRÉER SNAPSHOTS ═══

# INTERFACE WORKSTATION:
# ═════════════════════

# Méthode 1: Menu principal
# ────────────────────────
# 1. Sélectionner VM dans library
# 2. Menu: VM -> Snapshot -> Take Snapshot...
# 3. Dialog box apparaît

# Méthode 2: Toolbar
# ─────────────────
# 1. Sélectionner VM
# 2. Clic icône caméra ([CAMERA]) dans toolbar
# 3. Dialog box apparaît

# Méthode 3: Raccourci clavier
# ────────────────────────────
# • Ctrl + M (Windows/Linux)
# • Cmd + M (macOS)


# SNAPSHOT DIALOG:
# ═══════════════

# ┌─────────────────────────────────────────────┐
# │ Take Snapshot                               │
# ├─────────────────────────────────────────────┤
# │ Name: [Avant-Update-Kernel            ]  │
# │                                             │
# │ Description: (Optional)                     │
# │ ┌─────────────────────────────────────────┐ │
# │ │ Snapshot before kernel 6.8 update     │ │
# │ │ Date: 2024-12-16 10:30                │ │
# │ │ Critical update - may break boot      │ │
# │ └─────────────────────────────────────────┘ │
# │                                             │
# │ [x] Snapshot the virtual machine's memory    │
# │   (Capture running applications state)     │
# │                                             │
# │ [ ] Quiesce guest file system                │
# │   (Requires VMware Tools)                  │
# │                                             │
# │          [Take Snapshot]  [Cancel]          │
# └─────────────────────────────────────────────┘

# CHAMPS:
# ──────

# Name (OBLIGATOIRE):
# • Court et descriptif
# • Caractères valides: lettres, chiffres, tirets, underscores
# • Éviter: espaces (remplacer par tirets)
# • Max: 80 caractères
# • Exemples:
#   [OK] "Avant-Update-System"
#   [OK] "Config-Reseau-OK"
#   [OK] "Before-Test-Script"
#   [X] "test" (trop vague)
#   [X] "my snapshot 123" (espaces problématiques)

# Description (OPTIONAL mais RECOMMANDÉ):
# • Contexte complet modification
# • Date/heure
# • Raison snapshot
# • Modifications prévues
# • Contact personne si shared
# • Max: 1000 caractères
# • Exemple complet:
#   """
#   Snapshot before Apache 2.4 -> Nginx migration
#   Date: 2024-12-16 14:00
#   Reason: Testing new web server config
#   Expected changes:
#   - Remove apache2 package
#   - Install nginx
#   - Port configs to nginx format
#   - Test site functionality
#   Rollback if: Site down > 5min OR performance degraded
#   Created by: admin@company.com
#   """

# Snapshot VM memory:
# • [x] Checked: Capture RAM + state processus
#   • VM running -> État EXACT capturé
#   • Revert -> Applications running identiques
#   • Taille: +RAM allouée (ex: VM 8GB = +8GB fichier)
#   • Durée: 30-90 secondes
# • [ ] Unchecked: Disque seul
#   • Revert -> VM boot normal
#   • Taille: Seulement delta disque
#   • Durée: 5-15 secondes

# Quiesce guest filesystem:
# • Nécessite: VMware Tools installé
# • [x] Checked: Application-consistent snapshot
#   • Sync filesystem
#   • Flush database caches
#   • Garantie cohérence données
#   • Use case: Production, databases
# • [ ] Unchecked: Crash-consistent snapshot
#   • Pas de coordination apps
#   • Possible perte données en cache
#   • Use case: Dev, test


# EXEMPLES CONFIGURATION:
# ══════════════════════

# Scénario 1: Update système dev
# ──────────────────────────────
# Name: Avant-Apt-Upgrade
# Description: System update before kernel 6.8
# [ ] Snapshot VM memory (VM peut reboot)
# [ ] Quiesce (pas critique)

# Scénario 2: Test script running app
# ───────────────────────────────────
# Name: Debug-Memory-Leak
# Description: Capture state app with memory leak issue
# [x] Snapshot VM memory (garde process exact)
# [ ] Quiesce (debug, pas production)

# Scénario 3: Backup database production
# ──────────────────────────────────────
# Name: Backup-MySQL-Daily
# Description: Daily backup before maintenance window
# [ ] Snapshot VM memory (pas nécessaire)
# [x] Quiesce (garantit cohérence MySQL)


# PROCESSUS CRÉATION:
# ══════════════════

# Après clic [Take Snapshot]:
# ───────────────────────────

# Console VMware affiche progression:
# ┌────────────────────────────────────┐
# │ Taking snapshot...                 │
# │ [████████████████░░░░] 75%         │
# │                                    │
# │ Quiescing guest file system...     │
# │ Creating delta disk...             │
# │ Saving memory state...             │
# └────────────────────────────────────┘

# Étapes internes:
# 1. Si quiesce enabled:
#    a. VMware Tools contacte guest OS
#    b. Sync filesystems ($ sync)
#    c. Signal apps flush caches (MySQL, PostgreSQL, etc)
#    d. Apps bloquées brièvement (1-2 secondes)

# 2. Création delta disk:
#    a. Disque original (.vmdk) passe READ-ONLY
#    b. Nouveau delta disk créé (000001-delta.vmdk)
#    c. Écritures futures -> delta disk

# 3. Si memory snapshot:
#    a. Suspend VM brièvement (pause)
#    b. Dump RAM -> fichier .vmsn
#    c. État CPU, registres sauvés
#    d. VM resume

# 4. Metadata snapshot:
#    a. Création .vmsd (snapshot database)
#    b. Enregistrement hierarchy snapshots
#    c. Timestamp, description sauvés

# Durée totale:
# • Sans memory: 10-30 secondes
# • Avec memory (8GB RAM): 30-90 secondes
# • Avec memory (32GB RAM): 2-4 minutes
# • Quiesce ajoute: 2-5 secondes


# VÉRIFICATION SNAPSHOT CRÉÉ:
# ═══════════════════════════

# Interface Workstation:
# ─────────────────────
# 1. VM -> Snapshot -> Snapshot Manager
# 2. Tree view s'affiche:
#
# ┌─────────────────────────────────────────┐
# │ Snapshot Manager - Ubuntu-Server        │
# ├─────────────────────────────────────────┤
# │ You Are Here: Avant-Apt-Upgrade         │
# │                                         │
# │ [TRIGRAM_FOR_HEAVEN] Ubuntu-Server (Base state)            │
# │   ├─ [CAMERA_WITH_FLASH] Avant-Apt-Upgrade               │
# │   │    2024-12-16 10:30                 │
# │   │    System update before kernel 6.8  │
# │   │    Size: 2.3 GB                     │
# │   └─ You Are Here                       │
# │                                         │
# │ [Go To] [Delete] [Revert] [Close]       │
# └─────────────────────────────────────────┘

# Filesystem vérification:
# ───────────────────────
# $ ls -lh /path/to/vm/
# -rw-------  1 user  staff   20G  Dec 16 09:00 Ubuntu-Server-flat.vmdk
# -rw-------  1 user  staff  500B  Dec 16 10:30 Ubuntu-Server-000001.vmdk
# -rw-------  1 user  staff  2.3G  Dec 16 10:35 Ubuntu-Server-000001-delta.vmdk
# -rw-------  1 user  staff  8.1G  Dec 16 10:30 Ubuntu-Server-Snapshot1.vmsn
# -rw-------  1 user  staff   10K  Dec 16 10:30 Ubuntu-Server.vmsd

# Fichiers expliqués:
# • Ubuntu-Server-flat.vmdk (20G): Disque original READ-ONLY
# • -000001.vmdk (500B): Descriptor delta disk
# • -000001-delta.vmdk (2.3G): Changements après snapshot
# • -Snapshot1.vmsn (8.1G): RAM state (8GB alloués)
# • .vmsd (10K): Snapshot metadata/hierarchy


# NAMING CONVENTIONS BEST PRACTICES:
# ══════════════════════════════════

# Format recommandé:
# [Action]-[Component]-[Date/Version]

# Exemples professionnels:
# • Before-Kernel-Upgrade-6.8
# • After-Apache-Config-v2
# • Pre-Database-Migration-2024-12
# • Working-State-After-Tests
# • Golden-Master-Clean-Install

# Éviter:
# [X] "test" - trop vague
# [X] "snapshot1" - numéro sans sens
# [X] "backup" - confusion avec vrais backups
# [X] "aaa" - garbage naming

# Convention équipe:
# • Préfixe standard: [Before|After|Working|Golden|Debug]
# • Date format: YYYY-MM-DD
# • Personne: initials (optional)
# • Exemple: Before-MySQL-Update-2024-12-16-JD


# AUTOMATISATION SNAPSHOTS (Advanced):
# ════════════════════════════════════

# PowerCLI (VMware PowerShell):
# ────────────────────────────
# Get-VM "Ubuntu-Server" | New-Snapshot `
#   -Name "Auto-Backup-$(Get-Date -Format 'yyyy-MM-dd-HH-mm')" `
#   -Description "Automated daily snapshot" `
#   -Memory:$false `
#   -Quiesce:$true

# vmrun (Command line Workstation):
# ─────────────────────────────────
# $ vmrun -T ws snapshot "/path/to/Ubuntu-Server.vmx" \
#     "Auto-Snapshot-$(date +%Y%m%d-%H%M%S)"

# Script bash automation:
# ──────────────────────
# #!/bin/bash
# VM_PATH="/home/user/VMs/Ubuntu-Server/Ubuntu-Server.vmx"
# SNAPSHOT_NAME="Auto-Backup-$(date +%Y%m%d-%H%M)"
# 
# vmrun -T ws snapshot "$VM_PATH" "$SNAPSHOT_NAME"
# 
# # Cleanup old snapshots (keep last 3)
# vmrun -T ws listSnapshots "$VM_PATH" | tail -n +4 | while read snap; do
#     vmrun -T ws deleteSnapshot "$VM_PATH" "$snap"
# done


# ERREURS COURANTES CRÉATION:
# ═══════════════════════════

# Erreur: "Insufficient disk space"
# ────────────────────────────────
# Cause: Pas assez espace pour delta disk + memory
# Espace requis: 
# • Delta disk: 10-30% taille disque VM
# • Memory state: 100% RAM allouée
# • Exemple: VM 50GB disque + 16GB RAM
#   -> Besoin: ~15GB (delta) + 16GB (memory) = 31GB minimum

# Solution:
# 1. Vérifier espace disponible:
#    • Windows: Disque Properties
#    • Linux: $ df -h /path/to/vms/
# 2. Libérer espace OU déplacer VM autre disque
# 3. Réduire RAM allouée VM si possible
# 4. Créer snapshot sans memory

# Erreur: "Unable to quiesce guest"
# ─────────────────────────────────
# Cause: VMware Tools pas installé ou pas running
# Message: "The quiesce operation is not supported"

# Vérification:
# Inside guest OS:
# $ systemctl status vmtoolsd
# [BLACK_CIRCLE] vmtoolsd.service - VMware Tools
#    Loaded: loaded
#    Active: active (running)  <- Doit être active

# Solution:
# • Installer VMware Tools (voir Partie 8)
# • Ou désactiver option Quiesce

# Erreur: "Snapshot operation failed"
# ──────────────────────────────────
# Causes possibles:
# 1. VM powered off (impossible memory snapshot)
#    -> Solution: Décocher "Snapshot VM memory"
# 
# 2. Disque independant configuré
#    -> Check VM Settings -> Hard Disk -> Advanced
#    -> Mode doit être "Dependent" (pas Independent)
# 
# 3. Snapshot déjà en cours
#    -> Attendre fin snapshot précédent
# 
# 4. Permissions fichiers
#    -> Vérifier user a droits écriture dossier VM

# Erreur: "Maximum snapshot depth exceeded"
# ─────────────────────────────────────────
# Cause: Trop snapshots chain (limite 31 niveaux)
# Solution: Consolider snapshots existants


# ═══ 6.3 GÉRER SNAPSHOTS ═══

# SNAPSHOT MANAGER INTERFACE:
# ═══════════════════════════

# Accès Snapshot Manager:
# ──────────────────────
# VM -> Snapshot -> Snapshot Manager
# Raccourci: Ctrl + Shift + M

# Interface layout:
# ────────────────
# ┌──────────────────────────────────────────────────────────────┐
# │ Snapshot Manager - Ubuntu-Server                 [×]         │
# ├──────────────────────────────────────────────────────────────┤
# │ ┌────────────────────────────┐ ┌──────────────────────────┐ │
# │ │ Snapshot Tree              │ │ Snapshot Information     │ │
# │ │                            │ │                          │ │
# │ │ [TRIGRAM_FOR_HEAVEN] Ubuntu-Server            │ │ Name: Before-Update      │ │
# │ │   ├─ [CAMERA_WITH_FLASH] Before-Update      │ │ Date: Dec 16, 10:30     │ │
# │ │   │    (2.3 GB)            │ │ Description:             │ │
# │ │   │                        │ │ System kernel update     │ │
# │ │   ├─ [CAMERA_WITH_FLASH] After-Config       │ │ before testing           │ │
# │ │   │   │ (1.8 GB)           │ │                          │ │
# │ │   │   └─ [CAMERA_WITH_FLASH] Working-State  │ │ Size: 2.3 GB             │ │
# │ │   │        (0.5 GB)        │ │ Type: Disk only          │ │
# │ │   │        You Are Here <- │ │                          │ │
# │ └────────────────────────────┘ └──────────────────────────┘ │
# │                                                              │
# │ [Go To] [Delete] [Delete All] [Revert] [Close]              │
# └──────────────────────────────────────────────────────────────┘

# Éléments interface:
# ──────────────────

# Snapshot Tree (gauche):
# • Vue hiérarchique snapshots
# • Icône [CAMERA_WITH_FLASH] = snapshot
# • Flèche "You Are Here" = état actuel VM
# • Taille entre parenthèses = espace utilisé
# • Structure arborescente montre relations parent-enfant

# Snapshot Information (droite):
# • Name: Nom snapshot
# • Date: Date création
# • Description: Description complète
# • Size: Espace disque utilisé
# • Type: Disk only OU Disk + Memory


# HIÉRARCHIE SNAPSHOTS:
# ════════════════════

# Structure linéaire (simple):
# ──────────────────────────
# Base VM
#   └─ Snapshot 1
#       └─ Snapshot 2
#           └─ Snapshot 3 (You Are Here)

# Exemple:
# Ubuntu-Server (base install)
#   └─ After-Updates (après apt upgrade)
#       └─ After-Apache-Install (web server installé)
#           └─ After-Config (configuration finale)

# Structure branchée (avancé):
# ───────────────────────────
# Base VM
#   ├─ Branch A: Test Apache
#   │   └─ Apache-Working
#   └─ Branch B: Test Nginx
#       └─ Nginx-Working

# Use case branching:
# • Tester 2 configurations différentes
# • Comparer approches
# • Développement parallèle

# Exemple concret:
# Ubuntu-Server
#   ├─ Database-PostgreSQL
#   │   ├─ PG-Config-1
#   │   └─ PG-Config-2
#   └─ Database-MySQL
#       ├─ MySQL-Config-1
#       └─ MySQL-Config-2


# GO TO SNAPSHOT:
# ══════════════

# Fonction: Naviguer vers snapshot spécifique

# QUAND utiliser:
# • Retourner état précédent SANS supprimer work actuel
# • Comparer différentes configurations
# • Tester état snapshot sans commitment

# COMMENT:
# ───────
# 1. Snapshot Manager -> Sélectionner snapshot cible
# 2. Clic [Go To]
# 3. Confirmation dialog:

# ┌──────────────────────────────────────────────┐
# │ Go To Snapshot                               │
# ├──────────────────────────────────────────────┤
# │ Going to snapshot "Before-Update" will:      │
# │                                              │
# │ • Create snapshot of current state           │
# │   (preserves your current work)              │
# │ • Restore VM to snapshot state               │
# │                                              │
# │ Current state will be saved as:              │
# │ "Ubuntu-Server-Snapshot-20241216-1030"       │
# │                                              │
# │ [x] Create snapshot of current state           │
# │                                              │
# │          [Go To]          [Cancel]           │
# └──────────────────────────────────────────────┘

# Option "Create snapshot of current state":
# • [x] Checked (RECOMMANDÉ): Sauvegarde état actuel avant go to
#   -> Permet revenir après si besoin
#   -> Zéro perte données
# • [ ] Unchecked: Perd changements actuels!
#   -> DANGEREUX si work non sauvegardé

# Après [Go To]:
# ─────────────
# 1. VM s'arrête si running
# 2. État snapshot restauré
# 3. VM redémarre au snapshot state
# 4. "You Are Here" déplacé vers snapshot cible
# 5. Ancien état sauvegardé (si option checked)

# Structure après Go To:
# ─────────────────────
# AVANT:
# Base
#   └─ Before-Update
#       └─ After-Update (You Are Here)

# APRÈS Go To "Before-Update":
# Base
#   └─ Before-Update (You Are Here)
#       ├─ Saved-State-20241216 (ancien état)
#       └─ After-Update


# REVERT TO SNAPSHOT:
# ══════════════════

# Fonction: Annuler tous changements, retour snapshot

# QUAND utiliser:
# • Modification a cassé système
# • Test failed, besoin rollback
# • Annuler complètement work actuel
# • Recommencer from scratch

# DIFFÉRENCE Go To vs Revert:
# ───────────────────────────
# GO TO:
# • Sauvegarde état actuel (option)
# • Navigation bidirectionnelle
# • Garde historique complet

# REVERT:
# • SUPPRIME état actuel!
# • Rollback destructif
# • Perd tous changements non snapshotés

# COMMENT Revert:
# ──────────────
# 1. Snapshot Manager -> Sélectionner snapshot
# 2. Clic [Revert]
# 3. Warning dialog:

# ┌──────────────────────────────────────────────┐
# │ [ATTENTION] Revert to Snapshot                        │
# ├──────────────────────────────────────────────┤
# │ Reverting to "Before-Update" will:           │
# │                                              │
# │ [X] DISCARD all changes since snapshot        │
# │ [X] DELETE current VM state                   │
# │ [X] CANNOT be undone                          │
# │                                              │
# │ All work after snapshot will be LOST:       │
# │ • File modifications                         │
# │ • Installed packages                         │
# │ • Configuration changes                      │
# │ • User data                                  │
# │                                              │
# │     [Revert]          [Cancel]               │
# └──────────────────────────────────────────────┘

# Après [Revert]:
# ──────────────
# 1. VM arrêtée
# 2. Delta disks actuels SUPPRIMÉS
# 3. VM restaurée état snapshot exact
# 4. VM redémarrée
# 5. Tous changements post-snapshot PERDUS

# Structure après Revert:
# ──────────────────────
# AVANT:
# Base
#   └─ Before-Update
#       └─ After-Failed-Update (You Are Here)
#           Delta: modifications cassées

# APRÈS Revert to "Before-Update":
# Base
#   └─ Before-Update (You Are Here)
# 
# [After-Failed-Update et son delta SUPPRIMÉS]

# Exemple cas réel:
# ────────────────
# 1. Snapshot "Before-Kernel-Update"
# 2. $ sudo apt upgrade -> Kernel 6.8 installé
# 3. Reboot -> Kernel panic!
# 4. VM ne boot plus
# 5. Force power off VM
# 6. Snapshot Manager -> Revert to "Before-Kernel-Update"
# 7. VM redémarre -> Kernel 6.5 (ancien, fonctionnel)
# 8. [OK] VM opérationnelle, update annulé


# DELETE SNAPSHOT:
# ═══════════════

# Fonction: Supprimer snapshot ET consolider changements

# POURQUOI supprimer snapshots?
# ─────────────────────────────
# • Libérer espace disque (delta disks volumineux)
# • Améliorer performance (reduce chain)
# • Cleanup après tests réussis
# • Maintenance régulière

# QUAND supprimer:
# ───────────────
# [OK] Test réussi, modifications validées
# [OK] Snapshot obsolète (> 72 heures)
# [OK] Manque espace disque
# [OK] Performance dégradée (longue chain)

# [ATTENTION] ATTENTION: Delete ≠ Revert!
# ──────────────────────────────
# DELETE snapshot:
# • Garde changements actuels
# • Consolide delta dans parent
# • Libère espace disque
# • Perd possibilité rollback

# REVERT snapshot:
# • Annule changements actuels
# • Retourne état snapshot
# • Garde snapshot existant

# COMMENT Delete:
# ──────────────
# 1. Snapshot Manager -> Sélectionner snapshot
# 2. Clic [Delete]
# 3. Confirmation:

# ┌──────────────────────────────────────────────┐
# │ Delete Snapshot                              │
# ├──────────────────────────────────────────────┤
# │ Deleting "Before-Update" will:               │
# │                                              │
# │ [OK] Keep all current changes                  │
# │ [OK] Merge delta disk into parent              │
# │ [OK] Free 2.3 GB disk space                    │
# │ [X] Remove ability to revert to this point    │
# │                                              │
# │ Consolidation may take several minutes       │
# │ depending on snapshot size.                  │
# │                                              │
# │          [Delete]          [Cancel]          │
# └──────────────────────────────────────────────┘

# Processus Delete (Backend):
# ──────────────────────────
# 1. VM suspendue brièvement
# 2. Delta disk consolidation:
#    • Lecture données delta
#    • Merge dans parent disk
#    • Validation écriture
# 3. Suppression fichiers snapshot:
#    • -000001-delta.vmdk
#    • -Snapshot1.vmsn
#    • -000001.vmdk descriptor
# 4. Update .vmsd metadata
# 5. VM resume

# Durée consolidation:
# • Petit delta (< 5GB): 30-90 secondes
# • Moyen delta (5-20GB): 2-5 minutes
# • Large delta (> 50GB): 10-30 minutes

# Exemple concret:
# ───────────────
# AVANT Delete:
# Base-flat.vmdk (20GB)
#   000001-delta.vmdk (3GB) <- Snapshot "Before-Update"
#     000002-delta.vmdk (5GB) <- Current state

# APRÈS Delete "Before-Update":
# Base-flat.vmdk (20GB)
#   000002-delta.vmdk (8GB) <- Consolidated (3GB + 5GB)

# Espace libéré: 3GB + overheads


# DELETE ALL SNAPSHOTS:
# ════════════════════

# Fonction: Supprimer TOUS snapshots, consolider full

# QUAND utiliser:
# • Fin phase test complète
# • Préparation production deployment
# • Cleanup complet VM
# • Performance critiquement dégradée

# COMMENT:
# ───────
# 1. Snapshot Manager -> [Delete All]
# 2. Confirmation sévère:

# ┌──────────────────────────────────────────────┐
# │ [ATTENTION] Delete All Snapshots                      │
# ├──────────────────────────────────────────────┤
# │ This will delete ALL 5 snapshots:            │
# │                                              │
# │ 1. Before-Update (2.3 GB)                    │
# │ 2. After-Config (1.8 GB)                     │
# │ 3. Working-State (0.5 GB)                    │
# │ 4. Test-Branch (3.2 GB)                      │
# │ 5. Final-State (1.1 GB)                      │
# │                                              │
# │ Total space to recover: 8.9 GB               │
# │                                              │
# │ [OK] Consolidate all changes into base disk    │
# │ [OK] Improve VM performance                    │
# │ [X] CANNOT revert to any previous state       │
# │ [X] CANNOT undo this operation                │
# │                                              │
# │ Consolidation estimated time: 15-25 minutes  │
# │                                              │
# │      [Delete All]          [Cancel]          │
# └──────────────────────────────────────────────┘

# Processus Delete All:
# ────────────────────
# 1. VM powered off (obligatoire)
# 2. Consolidation séquentielle:
#    a. Merge delta N -> delta N-1
#    b. Merge delta N-1 -> delta N-2
#    c. ... jusqu'à base disk
# 3. Suppression tous snapshot files
# 4. Base disk contient TOUS changements
# 5. .vmsd metadata reset

# Résultat final:
# ──────────────
# AVANT:
# Base-flat.vmdk (20GB)
#   + 5 delta disks (8.9GB total)
# = 28.9GB espace utilisé

# APRÈS:
# Base-flat.vmdk (28.9GB) <- Consolidated
# = 28.9GB espace utilisé (plus efficace)

# Performance improvement:
# • AVANT: Reads traverse 5 delta files
# • APRÈS: Reads direct from single file
# • IOPS improvement: +40-60%


# CONSOLIDATE SNAPSHOTS (Maintenance):
# ════════════════════════════════════

# Automatic consolidation warnings:
# ─────────────────────────────────
# VMware Workstation monitor snapshot chain

# Si chain > 10 snapshots OU delta size > 50GB:
# ┌──────────────────────────────────────────────┐
# │ [ATTENTION] Snapshot Chain Warning                    │
# ├──────────────────────────────────────────────┤
# │ VM "Ubuntu-Server" has excessive snapshots:  │
# │                                              │
# │ • 12 snapshots in chain                      │
# │ • 78 GB total delta disk size                │
# │                                              │
# │ This may cause:                              │
# │ • Slow performance (30-50% degradation)      │
# │ • Disk space issues                          │
# │ • Snapshot corruption risk                   │
# │                                              │
# │ Recommended: Consolidate or delete snapshots │
# │                                              │
# │    [Consolidate Now]    [Remind Later]       │
# └──────────────────────────────────────────────┘

# Manual consolidation check:
# ──────────────────────────
# $ ls -lh /path/to/vm/*-delta.vmdk | wc -l
# 12  <- Trop de delta disks!

# $ du -sh /path/to/vm/*-delta.vmdk
# 78G  <- Trop volumineux!


# BEST PRACTICES SNAPSHOTS:
# ═════════════════════════

# 1. NAMING CONVENTION
#    ─────────────────
#    [OK] Descriptif: "Before-Kernel-6.8-Update"
#    [OK] Date: "Config-Backup-2024-12-16"
#    [OK] Version: "Apache-Config-v3"
#    [X] Générique: "test", "snap1"

# 2. SNAPSHOT LIFESPAN
#    ─────────────────
#    • Test court: < 24 heures
#    • Migration: < 48 heures
#    • Maximum: 72 heures
#    • > 1 semaine: DANGER!

# 3. SNAPSHOT QUANTITY
#    ─────────────────
#    • Optimal: 1-2 snapshots
#    • Maximum: 3-5 snapshots
#    • > 10 snapshots: Performance critique

# 4. CLEANUP ROUTINE
#    ───────────────
#    • Daily: Review active snapshots
#    • Weekly: Delete obsoletes
#    • Monthly: Full consolidation clean VMs

# 5. DOCUMENTATION
#    ─────────────
#    Toujours remplir Description field:
#    • Purpose snapshot
#    • Expected changes
#    • Rollback criteria
#    • Contact person

# 6. STORAGE PLANNING
#    ────────────────
#    Reserve space:
#    • VM disk: 50GB
#    • Expected snapshots: 3-5
#    • Reserve: 50GB × 30% × 5 = 75GB minimum

# 7. PRE-SNAPSHOT CHECKLIST
#    ──────────────────────
#    [x] Sufficient disk space available
#    [x] VM in consistent state (no active errors)
#    [x] Descriptive name chosen
#    [x] Description documented
#    [x] Cleanup plan (when to delete)

# 8. POST-TEST CLEANUP
#    ─────────────────
#    After successful test:
#    1. Validate changes work
#    2. Test rollback capability
#    3. Delete snapshot if satisfied
#    4. Document final state


# TROUBLESHOOTING SNAPSHOTS:
# ══════════════════════════

# Problème: "Unable to delete snapshot"
# ─────────────────────────────────────
# Erreur: "Snapshot deletion failed: File in use"
# 
# Causes:
# 1. VM running (delta disk verrouillé)
#    -> Solution: Power off VM, retry delete
# 
# 2. Antivirus scanning delta file
#    -> Solution: Exclure VM directory d'antivirus
# 
# 3. Backup software reading delta
#    -> Solution: Pause backup, retry
# 
# 4. Permissions insuffisantes
#    -> Solution: Vérifier droits utilisateur

# Problème: "Snapshot corruption detected"
# ───────────────────────────────────────
# Symptôme: VM ne boot plus, snapshot inaccessible
# 
# Recovery:
# 1. Power off VM
# 2. Backup .vmx et tous .vmdk
# 3. VMware Workstation -> File -> Virtual Machine Settings
# 4. Remove corrupted snapshot:
#    $ vmware-vdiskmanager -R Ubuntu-Server-000001.vmdk
# 5. Si échec: Recovery from backup

# Problème: "Consolidation takes too long"
# ────────────────────────────────────────
# Symptôme: Delete snapshot bloqué > 1 heure
# 
# Causes:
# • Très large delta (> 100GB)
# • Disk I/O lent (HDD vs SSD)
# • Antivirus interference
# 
# Solutions:
# 1. Patience (peut prendre heures si large)
# 2. Monitor progress:
#    • Task Manager -> Disk activity
#    • VM directory -> File size changes
# 3. Si vraiment bloqué > 4 heures:
#    • Kill VMware process
#    • Restore from backup
#    • Contact VMware support

# Problème: "Snapshot uses too much space"
# ───────────────────────────────────────
# Symptôme: Delta disk > VM disk size
# 
# Cause: Multiple snapshots + intensive writes
# 
# Solution:
# 1. Delete unnecessary snapshots
# 2. Consolidate remaining
# 3. Increase storage capacity
# 4. Monitor future snapshot growth


# ═══ 6.4 SNAPSHOTS LIGNE DE COMMANDE ═══

# VMRUN TOOL (CLI Workstation):
# ═════════════════════════════

# List snapshots:
# ──────────────
# $ vmrun -T ws listSnapshots "/path/to/VM.vmx"
# Total snapshots: 3
# Before-Update
# After-Config
# Working-State

# Create snapshot:
# ───────────────
# $ vmrun -T ws snapshot "/path/to/VM.vmx" "Snapshot-Name"
# 
# Options:
# $ vmrun -T ws snapshot "/path/to/VM.vmx" "Snapshot-Name" \
#     -description "Detailed description here"

# Delete snapshot:
# ───────────────
# $ vmrun -T ws deleteSnapshot "/path/to/VM.vmx" "Snapshot-Name"

# Revert to snapshot:
# ──────────────────
# $ vmrun -T ws revertToSnapshot "/path/to/VM.vmx" "Snapshot-Name"

# Automation script example:
# ─────────────────────────
# #!/bin/bash
# VM_PATH="/home/user/VMs/Ubuntu-Server/Ubuntu-Server.vmx"
# TIMESTAMP=$(date +%Y%m%d-%H%M%S)
# SNAP_NAME="Auto-Backup-$TIMESTAMP"
# 
# # Create snapshot
# echo "Creating snapshot: $SNAP_NAME"
# vmrun -T ws snapshot "$VM_PATH" "$SNAP_NAME"
# 
# # Keep only last 5 snapshots
# SNAPS=$(vmrun -T ws listSnapshots "$VM_PATH" | tail -n +2)
# COUNT=$(echo "$SNAPS" | wc -l)
# 
# if [ $COUNT -gt 5 ]; then
#     echo "$SNAPS" | head -n $(($COUNT - 5)) | while read snap; do
#         echo "Deleting old snapshot: $snap"
#         vmrun -T ws deleteSnapshot "$VM_PATH" "$snap"
#     done
# fi


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 6: SNAPSHOTS ET GESTION DES ÉTATS VM
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# PARTIE 7: CLONAGE ET TEMPLATES VM
# ═══════════════════════════════════════════════════════════════════


# ═══ 7.1 COMPRENDRE LE CLONAGE VM ═══

# POURQUOI cloner VMs?
# ═══════════════════

# PROBLÈME: Créer VMs identiques répétitivement
# ─────────────────────────────────────────────

# Scénarios nécessitant VMs multiples similaires:
# • Cluster web servers (5 serveurs Apache identiques)
# • Environnements dev/test/staging (3 VMs similaires)
# • Lab formation (20 VMs étudiants identiques)
# • Test compatibilité (multiple OS versions)

# Méthode manuelle (SANS clonage):
# ────────────────────────────────
# Pour 5 web servers:
# 1. Installer Ubuntu Server VM1 (30 min)
# 2. Configurer réseau, users, SSH (20 min)
# 3. Installer Apache, PHP, MySQL (30 min)
# 4. Configurer firewall, security (20 min)
# 5. Total VM1: 100 minutes
# 
# 6. RÉPÉTER étapes 1-5 pour VM2 (100 min)
# 7. RÉPÉTER pour VM3 (100 min)
# 8. RÉPÉTER pour VM4 (100 min)
# 9. RÉPÉTER pour VM5 (100 min)
# 
# Total: 500 minutes = 8.3 heures!
# Risque: Erreurs différentes chaque installation
# Problème: Configurations inconsistantes

# Solution AVEC clonage:
# ─────────────────────
# 1. Créer VM1 parfaite (100 min)
# 2. Cloner VM1 -> VM2 (3 min)
# 3. Cloner VM1 -> VM3 (3 min)
# 4. Cloner VM1 -> VM4 (3 min)
# 5. Cloner VM1 -> VM5 (3 min)
# 
# Total: 112 minutes = 1.9 heures!
# [OK] Gain temps: 75%
# [OK] Configurations identiques garanties
# [OK] Zéro erreur répétition


# AVANTAGES CLONAGE:
# ═════════════════

# [OK] Rapidité extrême (minutes vs heures)
# [OK] Consistance parfaite (clones identiques)
# [OK] Économie licensing (1 install OS -> N VMs)
# [OK] Déploiement scalable (10-100 VMs possibles)
# [OK] Testing facile (environnements isolés identiques)
# [OK] Disaster recovery (clones standby ready)
# [OK] Development workflows (dev/test/staging clones)


# ANALOGIE: Photocopie vs Réécriture manuelle
# ═══════════════════════════════════════════

# Document 50 pages à dupliquer pour 10 personnes:

# SANS photocopieuse (= sans clonage):
# • Réécrire manuellement 50 pages
# • Répéter 10 fois
# • Temps: 10 × 2 heures = 20 heures
# • Risque: Fautes frappe différentes chaque copie
# • Inconsistent quality

# AVEC photocopieuse (= clonage VM):
# • Document original parfait
# • Photocopier 10 exemplaires
# • Temps: 5 minutes
# • Résultat: 10 copies identiques parfaites
# • Perfect consistency


# TYPES DE CLONES:
# ════════════════

# 1. FULL CLONE (Clone complet)
#    ──────────────────────────
#    • Clone indépendant 100%
#    • Copie complète tous fichiers VM
#    • Taille: Identique VM source
#    • Parent VM peut être supprimé
#    • Use case: Production, VMs permanentes

# 2. LINKED CLONE (Clone lié)
#    ────────────────────────
#    • Clone partage disque parent
#    • Seulement différences stockées
#    • Taille: 5-20% VM source
#    • Parent VM OBLIGATOIRE (dépendance)
#    • Use case: Testing, développement temporaire

# 3. TEMPLATE (Modèle)
#    ─────────────────
#    • VM master optimisée pour clonage
#    • Généralement powered off
#    • Jamais démarrée (conserve état vierge)
#    • Source pour tous clones futurs


# FULL CLONE vs LINKED CLONE:
# ═══════════════════════════

# Full Clone:
# ──────────
# VM Source: Ubuntu-Server (20GB)
#   v [Clone Full]
# Clone: Ubuntu-Clone (20GB)
# 
# Fichiers Clone:
# • Ubuntu-Clone.vmx (config indépendante)
# • Ubuntu-Clone-flat.vmdk (20GB - copie complète)
# • Ubuntu-Clone.nvram
# 
# Relation: AUCUNE (totalement indépendant)
# Parent supprimable: [OK] OUI
# Portabilité: [OK] OUI (clone déplaçable seul)
# Performance: [OK] Native (pas overhead)
# Taille: [X] Large (disque complet dupliqué)

# Linked Clone:
# ────────────
# VM Source: Ubuntu-Server (20GB)
#   v [Clone Linked]
# Clone: Ubuntu-Linked (2GB)
# 
# Fichiers Clone:
# • Ubuntu-Linked.vmx (config propre)
# • Ubuntu-Linked-000001.vmdk (descriptor)
# • Ubuntu-Linked-000001-delta.vmdk (2GB - différences)
# • Lien vers Ubuntu-Server-flat.vmdk (shared)
# 
# Relation: DÉPENDANT (partage base disk)
# Parent supprimable: [X] NON (clone cassé si parent supprimé)
# Portabilité: [X] NON (nécessite parent)
# Performance: [WHITE_UP-POINTING_TRIANGLE] Légère overhead (delta chain)
# Taille: [OK] Minimal (seulement changements)

# Exemple concret:
# ───────────────
# Créer 10 clones pour lab étudiant:
# 
# Full Clone:
# • VM source: 20GB
# • 10 clones: 10 × 20GB = 200GB espace requis
# 
# Linked Clone:
# • VM source: 20GB
# • 10 clones: 10 × 2GB = 20GB (seulement différences)
# • Total: 40GB espace requis
# • Économie: 80% espace!


# QUAND utiliser Full vs Linked:
# ══════════════════════════════

# FULL CLONE pour:
# • Production servers (performance critique)
# • VMs long-terme (jours/mois/années)
# • Déploiement distribué (différents datastores)
# • Backup/DR (clones indépendants)
# • Migration vers autre host
# • Maximum performance nécessaire

# LINKED CLONE pour:
# • Development rapide (test branches)
# • Labs temporaires (étudiants, training)
# • Testing multiple configs (A/B testing)
# • Économie espace disque critique
# • Clones court-terme (heures/jours)
# • Environnements éphémères


# ═══ 7.2 CRÉER CLONES ═══

# PRÉREQUIS CLONAGE:
# ═════════════════

# Avant cloner, VM source doit:
# [OK] Être powered off (éteinte)
# [OK] Pas de snapshots actifs (ou cloner depuis snapshot)
# [OK] Espace disque suffisant (full clone)
# [OK] VMware Tools installé (recommandé)

# Si VM running:
# $ VM -> Power -> Shut Down Guest
# Attendre shutdown complet


# CRÉER FULL CLONE:
# ════════════════

# Méthode Interface:
# ─────────────────

# 1. Sélectionner VM source dans Library
# 2. Right-click -> Manage -> Clone...
# 3. Clone Virtual Machine Wizard s'ouvre:

# ┌──────────────────────────────────────────────┐
# │ Clone Virtual Machine Wizard                 │
# ├──────────────────────────────────────────────┤
# │ Welcome to Clone Virtual Machine Wizard      │
# │                                              │
# │ This wizard helps you create a clone of      │
# │ your virtual machine.                        │
# │                                              │
# │ • Full clone: Complete independent copy      │
# │ • Linked clone: Shares parent disk           │
# │                                              │
# │              [Next >]          [Cancel]      │
# └──────────────────────────────────────────────┘

# ÉTAPE 1: Clone Source
# ─────────────────────
# ┌──────────────────────────────────────────────┐
# │ Clone Source                                 │
# ├──────────────────────────────────────────────┤
# │ Choose the source for the clone:             │
# │                                              │
# │ [FISHEYE] The current state in the virtual machine   │
# │    (Clone from current VM state)             │
# │                                              │
# │ [WHITE_CIRCLE] An existing snapshot                       │
# │    └─ [Select Snapshot...]                   │
# │       Use if you want to clone from          │
# │       specific snapshot state                │
# │                                              │
# │         [< Back]  [Next >]  [Cancel]         │
# └──────────────────────────────────────────────┘

# Options:
# • Current state: Clone VM exact état actuel
# • Existing snapshot: Clone depuis snapshot spécifique
#   -> Use case: Cloner état "clean install" snapshot

# ÉTAPE 2: Clone Type
# ───────────────────
# ┌──────────────────────────────────────────────┐
# │ Clone Type                                   │
# ├──────────────────────────────────────────────┤
# │ Select clone type:                           │
# │                                              │
# │ [FISHEYE] Create a full clone                        │
# │    • Independent VM (20GB)                   │
# │    • Can move or delete parent               │
# │    • Best performance                        │
# │    • Requires full disk space                │
# │                                              │
# │ [WHITE_CIRCLE] Create a linked clone                      │
# │    • Shares parent disk (~2GB)               │
# │    • Saves disk space                        │
# │    • Parent VM required                      │
# │    • Requires snapshot on parent             │
# │                                              │
# │         [< Back]  [Next >]  [Cancel]         │
# └──────────────────────────────────────────────┘

# Choisir selon use case
# Si linked clone sélectionné:
# -> Wizard crée automatiquement snapshot sur parent

# ÉTAPE 3: Name and Location
# ──────────────────────────
# ┌──────────────────────────────────────────────┐
# │ Name and Location                            │
# ├──────────────────────────────────────────────┤
# │ Virtual machine name:                        │
# │ [Ubuntu-Server-Clone-Web01            ]   │
# │                                              │
# │ Location:                                    │
# │ [D:\VMs\Production\Web-Cluster\       ]   │
# │                            [Browse...]       │
# │                                              │
# │ [x] Clone linked clone's parent                │
# │   (Copy parent VM to same location)          │
# │                                              │
# │         [< Back]  [Next >]  [Cancel]         │
# └──────────────────────────────────────────────┘

# Name conventions:
# • Source-Purpose-Number: "Ubuntu-Web01"
# • Environment-Type-ID: "Prod-Apache-01"
# • Descriptive: "WebServer-Clone-01"

# Location:
# • Organisé par projet/environnement
# • Exemples:
#   D:\VMs\Production\Web-Cluster\
#   D:\VMs\Development\TestEnv\
#   D:\VMs\Labs\Student-Lab\

# ÉTAPE 4: Ready to Clone
# ───────────────────────
# ┌──────────────────────────────────────────────┐
# │ Ready to Clone Virtual Machine               │
# ├──────────────────────────────────────────────┤
# │ Review clone settings:                       │
# │                                              │
# │ Source VM: Ubuntu-Server                     │
# │ Clone type: Full Clone                       │
# │ Clone name: Ubuntu-Server-Clone-Web01        │
# │ Location: D:\VMs\Production\Web-Cluster\     │
# │                                              │
# │ Estimated disk space required: 20 GB         │
# │ Estimated time: 5-10 minutes                 │
# │                                              │
# │ Click Finish to begin cloning process.       │
# │                                              │
# │         [< Back]  [Finish]  [Cancel]         │
# └──────────────────────────────────────────────┘


# PROCESSUS CLONAGE:
# ═════════════════

# Progress dialog:
# ┌──────────────────────────────────────────────┐
# │ Cloning Virtual Machine...                   │
# ├──────────────────────────────────────────────┤
# │ [██████████████████░░░░░░] 65%               │
# │                                              │
# │ Copying virtual disk...                      │
# │ 13.2 GB of 20 GB copied                      │
# │                                              │
# │ Estimated time remaining: 3 minutes          │
# │                                              │
# │                          [Cancel]            │
# └──────────────────────────────────────────────┘

# Étapes internes (Full Clone):
# ────────────────────────────
# 1. Création dossier destination
# 2. Copie .vmx file (config VM)
#    -> UUID généré unique
#    -> MAC addresses régénérées
# 3. Copie .nvram (BIOS/UEFI settings)
# 4. Copie disk files (.vmdk):
#    • Lecture source -flat.vmdk
#    • Écriture clone -flat.vmdk
#    • Copie block-by-block
#    • Vérification checksums
# 5. Update clone .vmx paths
# 6. Création .lck directory

# Durée Full Clone:
# • 20GB VM sur HDD: 10-15 minutes
# • 20GB VM sur SSD: 3-5 minutes
# • 100GB VM sur HDD: 45-60 minutes
# • 100GB VM sur SSD: 15-20 minutes

# Étapes internes (Linked Clone):
# ──────────────────────────────
# 1. Création snapshot sur parent (si pas existant)
# 2. Création dossier clone
# 3. Copie .vmx file
# 4. Création delta disk:
#    • Parent disk reste shared
#    • Nouveau -delta.vmdk (vide initial)
#    • Pointeur vers parent
# 5. UUID et MAC unique générés

# Durée Linked Clone:
# • Tout VM: 30-90 secondes (indépendant taille!)


# APRÈS CLONAGE:
# ═════════════

# Clone apparaît dans Library:
# ┌─────────────────────────────┐
# │ My Computer                 │
# │  ├─ Ubuntu-Server (original)│
# │  └─ Ubuntu-Server-Clone-Web01 │
# └─────────────────────────────┘

# Premier boot clone:
# ──────────────────

# Si VMware Tools installé:
# ┌──────────────────────────────────────────────┐
# │ Virtual Machine Message                      │
# ├──────────────────────────────────────────────┤
# │ This virtual machine might have been moved   │
# │ or copied.                                   │
# │                                              │
# │ In order to configure certain management     │
# │ and networking features, VMware needs to     │
# │ know if this VM was moved or copied.         │
# │                                              │
# │ If you don't know, answer "I copied it".     │
# │                                              │
# │        [I moved it]    [I copied it]         │
# └──────────────────────────────────────────────┘

# Choisir "I copied it":
# • Génère nouveau UUID
# • Génère nouvelles MAC addresses
# • Reset machine-id système
# • Prévient conflits réseau

# Choisir "I moved it":
# • Garde UUID original
# • Garde MAC addresses
# • Use case: Migration VM entre hosts

# TOUJOURS choisir "I copied it" pour clones!


# PERSONNALISATION CLONE APRÈS BOOT:
# ═══════════════════════════════════

# 1. MODIFIER HOSTNAME
#    ─────────────────
# Clone hérite hostname source!
# Changement nécessaire pour éviter conflits

# Ubuntu/Debian:
# $ sudo hostnamectl set-hostname web01-clone
# $ sudo nano /etc/hosts
# Modifier: 127.0.1.1 ubuntu-server -> 127.0.1.1 web01-clone
# 
# Vérifier:
# $ hostname
# web01-clone

# 2. MODIFIER IP STATIQUE (si configurée)
#    ────────────────────────────────────
# Clone garde IP source -> CONFLIT réseau!

# $ sudo nano /etc/netplan/00-installer-config.yaml
# Changer:
# addresses: [192.168.120.100/24]  <- Source IP
# ->
# addresses: [192.168.120.101/24]  <- Nouvelle IP unique
# 
# $ sudo netplan apply

# 3. RÉGÉNÉRER SSH HOST KEYS
#    ───────────────────────
# Clone partage SSH keys source -> Sécurité compromise!

# $ sudo rm /etc/ssh/ssh_host_*
# $ sudo dpkg-reconfigure openssh-server
# $ sudo systemctl restart ssh
# 
# Vérifie nouveaux keys:
# $ sudo ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub

# 4. RÉGÉNÉRER MACHINE-ID
#    ────────────────────
# $ sudo rm /etc/machine-id
# $ sudo systemd-machine-id-setup
# $ cat /etc/machine-id
# [nouveau ID unique généré]

# 5. CLEAR LOGS (OPTIONAL)
#    ─────────────────────
# Supprimer logs source dans clone:
# $ sudo truncate -s 0 /var/log/*.log
# $ sudo truncate -s 0 /var/log/**/*.log

# 6. NETPLAN DHCP (alternative IP statique)
#    ──────────────────────────────────────
# Si clones multiples, DHCP simplifie:
# $ sudo nano /etc/netplan/00-installer-config.yaml
# dhcp4: true  <- Active DHCP
# Supprimer: addresses, routes, nameservers
# $ sudo netplan apply


# CRÉER LINKED CLONE:
# ══════════════════

# Wizard identical, sauf:
# ──────────────────────

# Step 2: Clone Type
# [WHITE_CIRCLE] Create a linked clone (sélectionner)

# Note importante:
# ┌──────────────────────────────────────────────┐
# │ ⓘ Information                                │
# ├──────────────────────────────────────────────┤
# │ A snapshot will be created on the parent VM  │
# │ "Ubuntu-Server" to support linked cloning.   │
# │                                              │
# │ Snapshot name: "Clone-Snapshot"              │
# │                                              │
# │ This snapshot must not be deleted while      │
# │ linked clones exist.                         │
# │                                              │
# │                   [OK]                       │
# └──────────────────────────────────────────────┘

# Clone rapide créé:
# • Durée: 30-60 secondes
# • Taille initiale: ~500MB-2GB
# • Croissance: +10-30% source VM selon usage

# Structure fichiers Linked Clone:
# ────────────────────────────────
# Parent VM:
# Ubuntu-Server/
#   Ubuntu-Server.vmx
#   Ubuntu-Server-flat.vmdk (20GB)
#   Ubuntu-Server-Snapshot1.vmsn  <- Snapshot clone
# 
# Linked Clone:
# Ubuntu-Linked-Clone/
#   Ubuntu-Linked-Clone.vmx
#   Ubuntu-Linked-Clone-000001.vmdk (descriptor)
#   Ubuntu-Linked-Clone-000001-delta.vmdk (2GB)
#   -> Pointe vers ../Ubuntu-Server/Ubuntu-Server-flat.vmdk

# DÉPENDANCE: Si parent supprimé, clone CASSÉ!


# CONVERTIR LINKED -> FULL CLONE:
# ══════════════════════════════

# Si linked clone devenu permanent:
# ────────────────────────────────

# 1. Power off linked clone
# 2. VM Settings -> Hard Disk -> Advanced
# 3. Clic [Utilities] -> Convert to Independent
# 4. Dialog confirmation:

# ┌──────────────────────────────────────────────┐
# │ Convert to Independent Disk                  │
# ├──────────────────────────────────────────────┤
# │ This will consolidate the linked clone disk  │
# │ into a full independent disk.                │
# │                                              │
# │ Process will:                                │
# │ • Merge parent and delta disk                │
# │ • Create new full disk (20GB)                │
# │ • Break link to parent VM                    │
# │ • Free clone from parent dependency          │
# │                                              │
# │ Estimated time: 10-15 minutes                │
# │ Disk space required: 20 GB                   │
# │                                              │
# │          [Convert]          [Cancel]         │
# └──────────────────────────────────────────────┘

# Après conversion:
# • Clone devenu full (indépendant)
# • Parent VM peut être supprimé
# • Taille augmente vers source size


# ═══ 7.3 TEMPLATES VM ═══

# POURQUOI créer templates?
# ════════════════════════

# Template = VM master optimisée pour clonage répété

# SANS template:
# • Clone Ubuntu-Server-Prod
# • Clone contient: logs production, configs spécifiques, données temporaires
# • Nécessite cleanup manuel après chaque clone
# • Inconsistent results

# AVEC template:
# • Clone Ubuntu-Server-Template (vierge, optimisé)
# • Clone propre, générique, ready deployment
# • Zéro cleanup nécessaire
# • Consistent results garantis


# CRÉER GOLDEN TEMPLATE:
# ═════════════════════

# Template = Golden Master (état parfait)

# Processus création:
# ──────────────────

# 1. CRÉER VM DE BASE
#    ────────────────
# • Installation OS propre
# • Partitioning optimal
# • Configurations minimales

# 2. INSTALLER COMPOSANTS COMMUNS
#    ────────────────────────────
# Tous packages nécessaires TOUS clones:
# 
# $ sudo apt update && sudo apt upgrade -y
# $ sudo apt install -y \
#     vim \
#     curl \
#     wget \
#     git \
#     htop \
#     net-tools \
#     openssh-server \
#     ufw \
#     fail2ban
# 
# $ sudo apt install -y python3 python3-pip
# $ sudo apt install -y build-essential

# 3. CONFIGURER SÉCURITÉ DE BASE
#    ───────────────────────────
# SSH hardening:
# $ sudo nano /etc/ssh/sshd_config
# PermitRootLogin no
# PasswordAuthentication yes (change après deployment)
# PubkeyAuthentication yes
# 
# Firewall:
# $ sudo ufw default deny incoming
# $ sudo ufw default allow outgoing
# $ sudo ufw allow ssh
# $ sudo ufw --force enable

# 4. INSTALLER VMWARE TOOLS
#    ──────────────────────
# (Voir Partie 8 détaillée)
# $ sudo apt install -y open-vm-tools

# 5. CRÉER USERS STANDARDS
#    ─────────────────────
# User admin générique:
# $ sudo adduser adminuser
# $ sudo usermod -aG sudo adminuser

# 6. CONFIGURATIONS RÉSEAU GÉNÉRIQUES
#    ─────────────────────────────────
# DHCP pour flexibilité (changeable après clone):
# $ sudo nano /etc/netplan/00-installer-config.yaml
# network:
#   version: 2
#   ethernets:
#     ens33:
#       dhcp4: true

# 7. OPTIMISER POUR CLONAGE
#    ──────────────────────
# Clear history:
# $ history -c
# $ > ~/.bash_history
# 
# Clear logs:
# $ sudo truncate -s 0 /var/log/*.log
# $ sudo truncate -s 0 /var/log/**/*.log
# 
# Clear tmp:
# $ sudo rm -rf /tmp/*
# $ sudo rm -rf /var/tmp/*
# 
# Clear caches:
# $ sudo apt clean
# $ sudo apt autoclean

# 8. GÉNÉRALISER SYSTÈME (SYSPREP équivalent)
#    ────────────────────────────────────────
# Remove machine-specific IDs:
# $ sudo rm /etc/machine-id
# $ sudo touch /etc/machine-id
# 
# Remove SSH host keys (régénérés au clone):
# $ sudo rm /etc/ssh/ssh_host_*
# 
# Clear network configs:
# $ sudo rm /etc/netplan/*
# Créer config générique DHCP

# 9. SHUTDOWN PROPRE
#    ───────────────
# $ sudo shutdown -h now

# 10. MARQUER COMME TEMPLATE
#     ──────────────────────
# Renommer VM:
# • Ubuntu-Server -> Ubuntu-Server-Template-24.04
# 
# Documentation:
# • Description: "Golden template Ubuntu Server 24.04 LTS"
# • Date création
# • Packages installés
# • Version VMware Tools


# TEMPLATE BEST PRACTICES:
# ═══════════════════════

# [OK] NAMING: Suffix "-Template" ou "Golden-Master"
# [OK] JAMAIS démarrer template (garde état vierge)
# [OK] VERSION: Inclure OS version dans nom
# [OK] DOCUMENTATION: Liste packages/configs
# [OK] UPDATE: Créer nouveau template pour updates
#   (Ubuntu-Template-24.04-v1, v2, v3...)
# [OK] SNAPSHOT: Créer snapshot template avant modifications
# [OK] SEPARATE STORAGE: Dossier dédié templates
#   D:\VMs\Templates\
# [OK] READ-ONLY: Protéger template accidental changes

# Organisation templates:
# ──────────────────────
# D:\VMs\Templates\
#   ├─ Ubuntu-Server-24.04-Template/
#   ├─ Ubuntu-Desktop-24.04-Template/
#   ├─ Debian-12-Template/
#   ├─ Windows-Server-2022-Template/
#   └─ CentOS-Stream-9-Template/


# CLONER DEPUIS TEMPLATE:
# ══════════════════════

# Workflow standard:
# ─────────────────

# 1. Right-click Template -> Manage -> Clone
# 2. Wizard: Current state
# 3. Type: Full Clone (production) OU Linked (dev)
# 4. Name: Descriptive + number
#    "WebServer-Prod-01"
#    "DBServer-Dev-05"
# 5. Location: Appropriate folder
# 6. Clone created
# 7. Boot clone
# 8. "I copied it" dialog
# 9. Personnaliser:
#    • Hostname
#    • IP (ou DHCP)
#    • SSH keys
#    • Machine-ID
# 10. Deploy ready!

# Example déploiement cluster:
# ───────────────────────────
# Template: Ubuntu-Server-Template-24.04
# 
# Clones créés:
# 1. WebServer-01 (192.168.120.101)
# 2. WebServer-02 (192.168.120.102)
# 3. WebServer-03 (192.168.120.103)
# 4. LoadBalancer-01 (192.168.120.100)
# 5. DBServer-01 (192.168.120.110)
# 
# Total deployment temps: 30 minutes
# vs manuel: 6+ heures


# TEMPLATE VERSIONING:
# ═══════════════════

# Update strategy:
# ───────────────

# Template initial:
# Ubuntu-Template-24.04-v1.0 (June 2024)
# • Base install
# • Common packages

# Mise à jour mineure:
# Ubuntu-Template-24.04-v1.1 (July 2024)
# • Security patches
# • Updated packages
# • Minor config changes

# Mise à jour majeure:
# Ubuntu-Template-24.04-v2.0 (September 2024)
# • New kernel
# • Major package updates
# • Architectural changes

# Nouvelle OS version:
# Ubuntu-Template-24.10-v1.0 (October 2024)
# • New Ubuntu release

# Retention policy:
# • Keep current + 1 previous major
# • Delete old after migration complete
# • Document version changes


# ═══ 7.4 CUSTOMIZATION AUTOMATISÉE ═══

# CLOUD-INIT (Linux):
# ══════════════════

# Cloud-init = Outil automatisation init VM

# Intégration VMware:
# ──────────────────
# 1. Template avec cloud-init installé:
# $ sudo apt install -y cloud-init

# 2. Configuration cloud-init:
# $ sudo nano /etc/cloud/cloud.cfg
# 
# datasource_list: [ VMware, NoCloud, None ]
# 
# cloud_init_modules:
#  - bootcmd
#  - write-files
#  - set_hostname
#  - update_hostname
#  - update_etc_hosts
#  - users-groups
#  - ssh

# 3. User-data example:
# ────────────────────
# File: user-data.yaml
# 
# #cloud-config
# hostname: webserver-01
# fqdn: webserver-01.example.com
# 
# users:
#   - name: deploy
#     groups: sudo
#     shell: /bin/bash
#     sudo: ALL=(ALL) NOPASSWD:ALL
#     ssh_authorized_keys:
#       - ssh-rsa AAAAB3Nza... user@host
# 
# packages:
#   - nginx
#   - mysql-server
#   - php8.1-fpm
# 
# write_files:
#   - path: /etc/nginx/sites-available/default
#     content: |
#       server {
#           listen 80;
#           root /var/www/html;
#           index index.php index.html;
#       }
# 
# runcmd:
#   - systemctl enable nginx
#   - systemctl start nginx
#   - systemctl enable mysql
#   - systemctl start mysql

# 4. VMware vApp Properties:
# ─────────────────────────
# VM Settings -> vApp Options -> Enable vApp options
# Properties -> Add properties pour cloud-init
# 
# Propriétés:
# • Hostname
# • IP address
# • Netmask
# • Gateway
# • DNS servers


# ANSIBLE POST-CLONE:
# ══════════════════

# Playbook customization:
# ──────────────────────
# File: customize-clone.yml
# 
# ---
# - hosts: newclone
#   become: yes
#   vars:
#     new_hostname: "{{ inventory_hostname }}"
#     new_ip: "{{ hostvars[inventory_hostname]['ansible_host'] }}"
#   
#   tasks:
#     - name: Set hostname
#       hostname:
#         name: "{{ new_hostname }}"
#     
#     - name: Update /etc/hosts
#       lineinfile:
#         path: /etc/hosts
#         regexp: '^127\.0\.1\.1'
#         line: "127.0.1.1 {{ new_hostname }}"
#     
#     - name: Configure static IP
#       template:
#         src: netplan.j2
#         dest: /etc/netplan/00-installer-config.yaml
#       notify: apply netplan
#     
#     - name: Regenerate SSH keys
#       shell: |
#         rm /etc/ssh/ssh_host_*
#         dpkg-reconfigure openssh-server
#       args:
#         creates: /etc/ssh/ssh_host_rsa_key
#     
#     - name: Regenerate machine-id
#       shell: |
#         rm /etc/machine-id
#         systemd-machine-id-setup
#   
#   handlers:
#     - name: apply netplan
#       command: netplan apply

# Execution:
# $ ansible-playbook -i inventory customize-clone.yml


# SCRIPT BASH POST-CLONE:
# ══════════════════════

# File: customize-clone.sh
# ───────────────────────
# #!/bin/bash
# # VM Clone Customization Script
# 
# # Variables
# NEW_HOSTNAME="$1"
# NEW_IP="$2"
# GATEWAY="192.168.120.2"
# DNS="8.8.8.8"
# 
# if [ -z "$NEW_HOSTNAME" ] || [ -z "$NEW_IP" ]; then
#     echo "Usage: $0 <hostname> <ip-address>"
#     exit 1
# fi
# 
# echo "[*] Customizing clone: $NEW_HOSTNAME ($NEW_IP)"
# 
# # Set hostname
# echo "[1/5] Setting hostname..."
# sudo hostnamectl set-hostname "$NEW_HOSTNAME"
# sudo sed -i "s/127.0.1.1.*/127.0.1.1 $NEW_HOSTNAME/" /etc/hosts
# 
# # Configure network
# echo "[2/5] Configuring network..."
# cat << EOF | sudo tee /etc/netplan/00-installer-config.yaml
# network:
#   version: 2
#   ethernets:
#     ens33:
#       dhcp4: false
#       addresses: [$NEW_IP/24]
#       routes:
#         - to: default
#           via: $GATEWAY
#       nameservers:
#         addresses: [$DNS]
# EOF
# sudo netplan apply
# 
# # Regenerate SSH keys
# echo "[3/5] Regenerating SSH keys..."
# sudo rm -f /etc/ssh/ssh_host_*
# sudo dpkg-reconfigure -f noninteractive openssh-server
# sudo systemctl restart ssh
# 
# # Regenerate machine-id
# echo "[4/5] Regenerating machine-id..."
# sudo rm -f /etc/machine-id
# sudo systemd-machine-id-setup
# 
# # Clear logs
# echo "[5/5] Clearing logs..."
# sudo truncate -s 0 /var/log/*.log 2>/dev/null
# 
# echo "[[OK]] Clone customization complete!"
# echo "    Hostname: $NEW_HOSTNAME"
# echo "    IP: $NEW_IP"
# echo ""
# echo "Please reboot VM to finalize changes."

# Usage:
# $ chmod +x customize-clone.sh
# $ sudo ./customize-clone.sh webserver-01 192.168.120.101


# ═══ 7.5 TROUBLESHOOTING CLONAGE ═══

# Problème: "Insufficient disk space"
# ──────────────────────────────────
# Full clone nécessite espace = taille VM source
# 
# Solution:
# 1. Vérifier espace disponible:
#    $ df -h /destination/path/
# 2. Libérer espace OU choisir autre destination
# 3. Alternative: Linked clone (10x moins espace)

# Problème: "Clone has duplicate UUID"
# ───────────────────────────────────
# Causes: Clonage manuel (copy/paste files)
# 
# Solution:
# 1. Toujours utiliser Clone wizard VMware
# 2. Si déjà copié manuellement:
#    a. Edit clone .vmx file
#    b. Supprimer ligne: uuid.bios = "..."
#    c. Boot VM -> Nouveau UUID généré auto

# Problème: "Network conflict - duplicate IP"
# ──────────────────────────────────────────
# Clone hérite IP source
# 
# Symptômes:
# • Ping IP -> Répond mais wrong hostname
# • SSH -> Connection refused ou connects wrong VM
# • Network intermittent
# 
# Solution:
# 1. Change clone IP:
#    $ sudo nano /etc/netplan/00-installer-config.yaml
#    addresses: [192.168.120.XXX/24]  <- Unique IP
#    $ sudo netplan apply
# 2. OU configure DHCP:
#    dhcp4: true

# Problème: "SSH connection refused - duplicate keys"
# ──────────────────────────────────────────────────
# Multiple VMs même SSH fingerprint
# 
# Client SSH warning:
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# 
# Solution clone:
# $ sudo rm /etc/ssh/ssh_host_*
# $ sudo dpkg-reconfigure openssh-server
# $ sudo systemctl restart ssh
# 
# Solution client:
# $ ssh-keygen -R 192.168.120.101

# Problème: "Linked clone broken after parent deletion"
# ─────────────────────────────────────────────────────
# Erreur: "Cannot open parent disk"
# 
# Cause: Parent VM supprimé
# 
# Prevention:
# [OK] JAMAIS supprimer parent si linked clones existent
# [OK] Documenter dépendances
# [OK] Convert linked -> full avant delete parent
# 
# Recovery (si trop tard):
# [X] Impossible récupérer complètement
# [WHITE_UP-POINTING_TRIANGLE] Possible si parent backup existe:
#   1. Restaurer parent VM backup
#   2. Linked clone fonctionne à nouveau


# BEST PRACTICES RÉSUMÉ:
# ═════════════════════

# TEMPLATES:
# [OK] Créer golden template clean
# [OK] Documentation complète
# [OK] Version control templates
# [OK] Separate storage
# [OK] Regular updates

# CLONAGE:
# [OK] Full clone: Production, long-terme
# [OK] Linked clone: Dev, test, temporaire
# [OK] Utiliser Clone wizard (pas copy/paste)
# [OK] "I copied it" dialog
# [OK] Personnaliser post-clone:
#   - Hostname
#   - IP address
#   - SSH keys
#   - Machine-id

# ORGANISATION:
# [OK] Naming conventions consistentes
# [OK] Folder structure logique
# [OK] Documentation relations parent-clone
# [OK] Tracking linked clone dependencies


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 7: CLONAGE ET TEMPLATES VM
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# PARTIE 8: VMWARE TOOLS - INSTALLATION ET UTILISATION
# ═══════════════════════════════════════════════════════════════════


# ═══ 8.1 QU'EST-CE QUE VMWARE TOOLS? ═══

# POURQUOI VMware Tools?
# ═════════════════════

# PROBLÈME: VM sans VMware Tools
# ──────────────────────────────

# Limitations VM "nue":
# [X] Résolution écran fixe 800x600 (impossible changer!)
# [X] Souris "capturée" (Ctrl+Alt pour libérer)
# [X] Performance graphique terrible (pas accélération)
# [X] Clipboard partagé impossible (copy/paste host<->guest)
# [X] Drag & drop fichiers impossible
# [X] Synchronisation temps approximative (drift ±5min/jour)
# [X] Shutdown graceful impossible (hard power off)
# [X] Snapshots inconsistants (crash-consistent seulement)
# [X] Monitoring VM aveugle (pas metrics RAM/CPU)
# [X] Network performance réduite (pas drivers optimisés)

# Exemple frustration utilisateur:
# ──────────────────────────────
# Dev: "Je travaille dans VM Ubuntu..."
# • Écran bloqué 800x600 -> Minuscule sur écran 4K
# • Copy code depuis host -> IMPOSSIBLE (pas clipboard)
# • Drag .zip dans VM -> IMPOSSIBLE
# • Horloge VM: 14:23, Host: 14:28 -> Logs décalés
# • Souris capturée -> Ctrl+Alt chaque switch
# -> Expérience utilisateur HORRIBLE!


# SOLUTION: VMware Tools installé
# ═══════════════════════════════

# Capabilities débloquées:
# [OK] Résolution dynamique (auto-resize, fullscreen parfait)
# [OK] Souris seamless (libre entre host/guest)
# [OK] Accélération graphique (3D support)
# [OK] Clipboard bidirectionnel (copy/paste host<->guest)
# [OK] Drag & drop files (host -> guest, guest -> host)
# [OK] Time sync précis (±1 seconde)
# [OK] Shutdown graceful (VM -> Power -> Shut Down Guest)
# [OK] Quiesced snapshots (application-consistent)
# [OK] Monitoring détaillé (CPU, RAM, disk, network metrics)
# [OK] Network drivers optimisés (VMXNET3 - 10Gbps capable)
# [OK] Shared folders (accès dossiers host depuis guest)
# [OK] Guest automation (scripts execution depuis host)

# Expérience transformée:
# ──────────────────────
# Dev: "Après VMware Tools install..."
# • Écran auto-resize parfait (utilise tout 4K)
# • Copy code host -> paste guest: INSTANTANÉ
# • Drag ISO/ZIP direct -> Fonctionne!
# • Horloge toujours sync parfait
# • Souris libre (pas Ctrl+Alt)
# -> Expérience native-like!


# ANALOGIE: Smartphone sans drivers
# ═════════════════════════════════

# Smartphone connecté PC:
# ──────────────────────

# SANS drivers:
# • PC détecte "Unknown device"
# • Pas access photos
# • Pas transfer files
# • Pas debugging
# • Charge uniquement (basique)

# AVEC drivers:
# • PC reconnait modèle exact
# • Access full filesystem
# • Transfer files rapide
# • Debugging apps
# • Backup/restore
# • Toutes fonctionnalités avancées

# VMware Tools = Driver suite VM
# Unlock toutes fonctionnalités avancées


# ARCHITECTURE VMWARE TOOLS:
# ══════════════════════════

# Components principaux:
# ─────────────────────

# 1. DRIVERS (Guest OS)
#    ─────────────────
#    • SVGA Driver: Accélération graphique
#    • VMXNET3: Network driver optimisé
#    • PVSCSI: Storage driver hautes performances
#    • VMware Balloon: Memory management
#    • Audio driver: Son optimisé

# 2. SERVICES (Daemons/Services)
#    ──────────────────────────
#    Linux:
#    • vmtoolsd: Service principal
#    • vmware-vmblock-fuse: Drag & drop
#    • vmhgfs-fuse: Shared folders
#    
#    Windows:
#    • VMTools Service: Service principal
#    • VMware User Process: User integration

# 3. USER SPACE TOOLS
#    ────────────────
#    • vmware-toolbox-cmd: CLI management
#    • vmware-user: Desktop integration
#    • vmware-checkvm: VM detection utility

# 4. KERNEL MODULES (Linux)
#    ──────────────────────
#    • vmw_balloon: Memory management
#    • vmw_vmci: VM communication
#    • vmw_vsock: Virtual sockets
#    • vmxnet3: Network driver
#    • vmw_pvscsi: SCSI driver


# COMMUNICATION VMWARE TOOLS:
# ═══════════════════════════

# Host (VMware) <-> Guest (VM):
# ───────────────────────────

# Channels communication:
# ┌─────────────┐
# │ VMware Host │
# │ (Workstation)│
# └──────┬──────┘
#        │
#        │ VMCI (VM Communication Interface)
#        │ Backdoor I/O Port
#        │
# ┌──────[BLACK_DOWN-POINTING_TRIANGLE]──────┐
# │ VMware Tools│
# │  (vmtoolsd) │
# │  in Guest   │
# └─────────────┘

# Exemple interaction:
# ───────────────────

# User action: Resize Workstation window
# 1. Host détecte resize
# 2. Host -> VMCI -> Guest: "New resolution: 1920x1080"
# 3. vmtoolsd reçoit message
# 4. vmtoolsd -> SVGA driver: Update resolution
# 5. Guest display: Auto-resize 1920x1080
# -> Seamless experience!

# User action: Copy text dans host
# 1. User Ctrl+C dans host
# 2. Host clipboard -> VMCI -> Guest
# 3. vmtoolsd: Update guest clipboard
# 4. User Ctrl+V dans guest
# 5. Text pasted!


# VERSIONS VMWARE TOOLS:
# ═════════════════════

# 1. OSP (Operating System Specific)
#    ──────────────────────────────
#    • Fourni par OS vendor
#    • Ubuntu: open-vm-tools package
#    • RedHat/CentOS: open-vm-tools package
#    • Debian: open-vm-tools package
#    • Maintenu OS repositories
#    • [OK] RECOMMANDÉ Linux moderne

# 2. VMWARE TOOLS (Bundled)
#    ──────────────────────
#    • Fourni avec Workstation/ESXi
#    • ISO: linux.iso, windows.iso
#    • Support ancien OS
#    • Windows principalement
#    • Mise à jour manuelle

# 3. OPEN-VM-TOOLS (Open Source)
#    ──────────────────────────
#    • Fork open source official
#    • Développé VMware + community
#    • Intégré distros Linux modernes
#    • Auto-updated via apt/yum
#    • [OK] Préféré pour Linux


# FEATURE COMPARISON:
# ══════════════════

# Feature                    | OSP/Open | Bundled
# ──────────────────────────┼──────────┼─────────
# Résolution dynamique       |    [OK]     |    [OK]
# Clipboard partagé          |    [OK]     |    [OK]
# Drag & drop                |    [OK]     |    [OK]
# Time synchronization       |    [OK]     |    [OK]
# Shared folders             |    [OK]     |    [OK]
# Guest automation           |    [OK]     |    [OK]
# Quiesced snapshots         |    [OK]     |    [OK]
# 3D acceleration            |    [OK]     |    [OK]
# Auto-update (Linux)        |    [OK]     |    [X]
# Unity mode (deprecated)    |    [X]     |    [WHITE_UP-POINTING_TRIANGLE]

# Recommendation:
# • Linux: open-vm-tools (OSP)
# • Windows: Bundled VMware Tools


# ═══ 8.2 INSTALLATION VMWARE TOOLS ═══

# LINUX (Ubuntu/Debian) - OPEN-VM-TOOLS:
# ═════════════════════════════════════

# MÉTHODE RECOMMANDÉE:
# ───────────────────

# Installation via package manager:
# ─────────────────────────────────

# Ubuntu/Debian:
# $ sudo apt update
# $ sudo apt install -y open-vm-tools

# Pour desktop avec GUI:
# $ sudo apt install -y open-vm-tools-desktop

# Packages open-vm-tools:
# ──────────────────────
# • open-vm-tools: Core tools (server)
#   - vmtoolsd daemon
#   - vmware-toolbox-cmd
#   - Drivers réseau/storage
#   - Time sync
#   - Guest automation

# • open-vm-tools-desktop: Desktop additions
#   - Clipboard partagé
#   - Drag & drop
#   - Auto-resize display
#   - Shared folders GUI
#   - 3D acceleration

# Vérifier installation:
# ─────────────────────
# $ dpkg -l | grep open-vm-tools
# ii  open-vm-tools         12.3.5-3   amd64   Open VMware Tools
# ii  open-vm-tools-desktop 12.3.5-3   amd64   Open VMware Tools (desktop)

# $ systemctl status vmtoolsd
# [BLACK_CIRCLE] vmtoolsd.service - Open VM Tools
#      Loaded: loaded (/lib/systemd/system/vmtoolsd.service; enabled)
#      Active: active (running) since Mon 2024-12-16 10:00:00 UTC
#    Main PID: 1234 (vmtoolsd)
#       Tasks: 2 (limit: 4655)
#      Memory: 8.5M
#         CPU: 123ms
#      CGroup: /system.slice/vmtoolsd.service
#              └─1234 /usr/bin/vmtoolsd

# [OK] Service running = VMware Tools actif!


# VÉRIFICATION FONCTIONNEMENT:
# ═══════════════════════════

# 1. Test résolution dynamique:
#    ─────────────────────────
#    • Resize Workstation window
#    • VM display auto-resize
#    -> [OK] Si fonctionne: Tools OK

# 2. Test clipboard:
#    ──────────────
#    • Copy text dans host
#    • Ctrl+V dans VM terminal
#    • Text doit paste
#    -> [OK] Si fonctionne: Clipboard OK

# 3. Test time sync:
#    ──────────────
#    $ vmware-toolbox-cmd stat sessionid
#    3456789  <- ID session (confirme tools communicate)
#    
#    $ vmware-toolbox-cmd timesync status
#    Enabled  <- Time sync actif

# 4. Test version:
#    ────────────
#    $ vmware-toolbox-cmd -v
#    12.3.5.12345 (build-12345)


# CONFIGURATION POST-INSTALL:
# ═══════════════════════════

# Enable time synchronization:
# ───────────────────────────
# $ sudo vmware-toolbox-cmd timesync enable
# Enabled

# $ vmware-toolbox-cmd timesync status
# Enabled

# Vérifier sync fonctionnel:
# $ date && vmware-toolbox-cmd stat raw text session
# Mon Dec 16 10:30:45 UTC 2024
# sessionId=3456789


# Enable shared folders:
# ─────────────────────
# (Voir section 8.4 Shared Folders)

# $ sudo mkdir -p /mnt/hgfs
# $ sudo mount -t fuse.vmhgfs-fuse .host:/ /mnt/hgfs -o allow_other


# LINUX (CentOS/RHEL/Fedora):
# ══════════════════════════

# CentOS Stream / RHEL:
# $ sudo dnf install -y open-vm-tools
# $ sudo dnf install -y open-vm-tools-desktop  # Si GUI

# Fedora:
# $ sudo dnf install -y open-vm-tools
# $ sudo dnf install -y open-vm-tools-desktop

# Enable service:
# $ sudo systemctl enable vmtoolsd
# $ sudo systemctl start vmtoolsd


# WINDOWS - VMWARE TOOLS ISO:
# ══════════════════════════

# Méthode installation:
# ────────────────────

# 1. MONTER ISO TOOLS
#    ────────────────
#    VM -> Install VMware Tools
#    
#    OU
#    
#    VM Settings -> CD/DVD -> Use ISO image:
#    Browse: C:\Program Files (x86)\VMware\VMware Workstation\windows.iso

# 2. WINDOWS AUTORUN
#    ───────────────
#    • CD/DVD drive apparaît Windows Explorer
#    • AutoPlay: "VMware Tools installation"
#    • Clic "Run setup64.exe"
#    
#    Si AutoPlay désactivé:
#    • Ouvrir D:\ (CD drive)
#    • Double-clic setup64.exe

# 3. SETUP WIZARD
#    ────────────
#    ┌──────────────────────────────────────┐
#    │ VMware Tools Setup Wizard            │
#    ├──────────────────────────────────────┤
#    │ Welcome to VMware Tools Setup        │
#    │                                      │
#    │ [Next >]                  [Cancel]   │
#    └──────────────────────────────────────┘

# 4. SETUP TYPE
#    ──────────
#    ┌──────────────────────────────────────┐
#    │ Setup Type                           │
#    ├──────────────────────────────────────┤
#    │ [FISHEYE] Typical                            │
#    │   Recommended features (standard)    │
#    │                                      │
#    │ [WHITE_CIRCLE] Complete                           │
#    │   All features                       │
#    │                                      │
#    │ [WHITE_CIRCLE] Custom                             │
#    │   Choose features manually           │
#    │                                      │
#    │ [< Back]  [Next >]       [Cancel]    │
#    └──────────────────────────────────────┘
#    
#    Choisir: Typical (recommandé)

# 5. INSTALLATION
#    ────────────
#    Progress bar installation
#    Durée: 2-5 minutes

# 6. REBOOT REQUIRED
#    ───────────────
#    ┌──────────────────────────────────────┐
#    │ Installation Complete                │
#    ├──────────────────────────────────────┤
#    │ VMware Tools installed successfully. │
#    │                                      │
#    │ You must restart your system for     │
#    │ changes to take effect.              │
#    │                                      │
#    │ [FISHEYE] Restart Now                        │
#    │ [WHITE_CIRCLE] Restart Later                      │
#    │                                      │
#    │              [Finish]                │
#    └──────────────────────────────────────┘
#    
#    -> Restart Now


# VÉRIFICATION WINDOWS:
# ════════════════════

# Après reboot:
# ────────────

# 1. Service running:
#    • Services -> VMware Tools Service
#    • Status: Running
#    • Startup: Automatic

# 2. Tray icon:
#    • System tray -> Icône VMware Tools
#    • Double-clic -> VMware Tools properties

# 3. Test résolution:
#    • Resize Workstation window
#    • Windows display auto-resize

# 4. Test clipboard:
#    • Copy text host
#    • Paste dans Notepad VM
#    -> [OK] Fonctionne


# ═══ 8.3 FONCTIONNALITÉS VMWARE TOOLS ═══

# TIME SYNCHRONIZATION:
# ════════════════════

# POURQUOI sync temps critique?
# ────────────────────────────

# Problèmes horloge désynchronisée:
# • Logs timestamps incorrects -> Debug impossible
# • Kerberos authentication fails (tolérance ±5min)
# • SSL certificates invalides (time-based)
# • Scheduled tasks execute wrong time
# • Database transactions corrupted
# • File timestamps incorrect

# Exemple problème réel:
# ────────────────────
# VM horloge: 10:00
# Host horloge: 10:30
# App log: "Error at 10:00"
# System log: "Network down 10:25"
# -> Impossible corréler events!


# TIME SYNC MECHANISMS:
# ════════════════════

# VMware Tools time sync:
# ──────────────────────
# • Check temps chaque minute
# • Si delta > 1 seconde -> Correction
# • Sync from host OU ESXi
# • Précision: ±1 seconde

# Events sync automatique:
# ───────────────────────
# • VM power on
# • VM resume from suspend
# • VM revert snapshot
# • Tools service restart
# • VM migration (vMotion)


# CONFIGURATION TIME SYNC:
# ═══════════════════════

# Linux:
# ─────

# Enable sync:
# $ sudo vmware-toolbox-cmd timesync enable

# Disable sync:
# $ sudo vmware-toolbox-cmd timesync disable

# Status:
# $ vmware-toolbox-cmd timesync status
# Enabled

# Manual sync:
# $ sudo vmware-toolbox-cmd timesync resync


# COMBINING NTP + VMware Time Sync:
# ═════════════════════════════════

# Best practice production:
# ────────────────────────

# 1. VMware time sync: Désactivé periodic
# 2. NTP: Source temps principal
# 3. VMware sync: Seulement boot/resume

# Configuration:
# $ sudo vmware-toolbox-cmd timesync disable

# Install NTP:
# $ sudo apt install -y chrony

# Configure chrony:
# $ sudo nano /etc/chrony/chrony.conf
# pool pool.ntp.org iburst
# 
# $ sudo systemctl enable chronyd
# $ sudo systemctl start chronyd

# Vérifier NTP sync:
# $ chronyc sources
# MS Name/IP address         Stratum Poll Reach LastRx Last sample
# ===============================================================================
# ^* ntp.ubuntu.com                2   6   377    23   -123us[-456us] +/-  15ms

# VMware sync seulement events:
# Edit: /etc/vmware-tools/tools.conf
# [vmbackup]
# enableSyncDriver = true
# 
# [time]
# # Sync time only on resume/power-on
# sync-on-resume = true
# sync-on-power-on = true


# CLIPBOARD PARTAGÉ:
# ═════════════════

# Enable/Disable:
# ──────────────

# Workstation:
# VM -> Settings -> Options -> Guest Isolation
# [x] Enable copy and paste
# [x] Enable drag and drop

# Directions:
# • Host -> Guest only
# • Guest -> Host only
# • Bidirectional (défaut)

# Security consideration:
# ──────────────────────
# Production VMs sensibles:
# [ ] Disable copy/paste (prevent data exfiltration)

# Dev/test:
# [x] Enable (convenience)


# DRAG AND DROP FILES:
# ═══════════════════

# Fonctionnement:
# ──────────────

# Host -> Guest:
# 1. Drag file from host desktop
# 2. Drop dans VM window
# 3. File copié vers guest (~/Downloads/ ou Desktop)

# Guest -> Host:
# 1. Drag file from VM
# 2. Drop sur host desktop
# 3. File copié vers host

# Limitations:
# • Single file/folder at time
# • Taille max: ~2GB (dépend config)
# • Pas de progress bar (large files)


# AUTOMATIC DISPLAY RESOLUTION:
# ════════════════════════════

# Auto-resize modes:
# ─────────────────

# 1. AUTOFIT WINDOW
#    ──────────────
#    View -> Autosize -> Autofit Window
#    • VM window resize -> Guest display resize
#    • Seamless experience
#    • [OK] Recommandé usage normal

# 2. AUTOFIT GUEST
#    ─────────────
#    View -> Autosize -> Autofit Guest
#    • Guest display drive window size
#    • Window resize match guest

# 3. FULLSCREEN
#    ──────────
#    View -> Full Screen (Ctrl+Alt+Enter)
#    • Guest utilise full host display
#    • Auto-resolution host native
#    • Multi-monitor support

# 4. UNITY MODE (deprecated)
#    ──────────────────────
#    • VM apps appear host desktop
#    • Seamless window integration
#    • [ATTENTION] Removed recent versions


# Manual resolution:
# ─────────────────

# Linux (si auto-resize pas functional):
# $ xrandr
# Screen 0: minimum 1 x 1, current 1920 x 1080, maximum 8192 x 8192
# Virtual-1 connected primary 1920x1080+0+0 ...
# 
# $ xrandr --output Virtual-1 --mode 1920x1080


# GUEST AUTOMATION:
# ════════════════

# vmrun COMMAND:
# ─────────────

# Execute commands dans guest depuis host:
# ───────────────────────────────────────

# Basic syntax:
# $ vmrun -T ws -gu username -gp password \
#     runProgramInGuest "/path/to/VM.vmx" \
#     "/path/to/program" "arg1" "arg2"

# Example Linux guest:
# $ vmrun -T ws -gu adminuser -gp mypassword \
#     runProgramInGuest "/home/user/VMs/Ubuntu-Server/Ubuntu-Server.vmx" \
#     "/bin/ls" "-la" "/home"

# Example Windows guest:
# $ vmrun -T ws -gu Administrator -gp mypassword \
#     runProgramInGuest "C:\VMs\Windows\Windows.vmx" \
#     "C:\Windows\System32\ipconfig.exe" "/all"


# COPY FILES HOST <-> GUEST:
# ═══════════════════════

# Copy host -> guest:
# $ vmrun -T ws -gu username -gp password \
#     copyFileFromHostToGuest "/path/to/VM.vmx" \
#     "/host/source/file.txt" \
#     "/guest/destination/file.txt"

# Copy guest -> host:
# $ vmrun -T ws -gu username -gp password \
#     copyFileFromGuestToHost "/path/to/VM.vmx" \
#     "/guest/source/file.txt" \
#     "/host/destination/file.txt"

# Example automation script:
# ─────────────────────────
# #!/bin/bash
# VM="/home/user/VMs/Ubuntu-Server/Ubuntu-Server.vmx"
# GUSER="adminuser"
# GPASS="password"
# 
# # Copy deploy script to guest
# vmrun -T ws -gu "$GUSER" -gp "$GPASS" \
#     copyFileFromHostToGuest "$VM" \
#     "/home/user/deploy.sh" \
#     "/tmp/deploy.sh"
# 
# # Execute script in guest
# vmrun -T ws -gu "$GUSER" -gp "$GPASS" \
#     runProgramInGuest "$VM" \
#     "/bin/bash" "/tmp/deploy.sh"
# 
# # Retrieve logs
# vmrun -T ws -gu "$GUSER" -gp "$GPASS" \
#     copyFileFromGuestToHost "$VM" \
#     "/var/log/deploy.log" \
#     "/home/user/logs/deploy.log"


# LIST PROCESSES IN GUEST:
# ════════════════════════

# $ vmrun -T ws -gu username -gp password \
#     listProcessesInGuest "/path/to/VM.vmx"
# 
# Output:
# PID   Name
# ───────────────────────
# 1     /sbin/init
# 123   /usr/sbin/sshd
# 456   /usr/bin/vmtoolsd
# 789   /usr/sbin/apache2


# KILL PROCESS IN GUEST:
# ═════════════════════

# $ vmrun -T ws -gu username -gp password \
#     killProcessInGuest "/path/to/VM.vmx" 789


# ═══ 8.4 SHARED FOLDERS ═══

# POURQUOI shared folders?
# ═══════════════════════

# Use cases:
# • Transfer files host <-> guest (alternative drag&drop)
# • Access host projects depuis guest VM
# • Share datasets entre multiple VMs
# • Development: Code host, run guest
# • Backup: Guest files accessible host

# Example workflow:
# ────────────────
# Dev environment:
# • Code editor: Host (VSCode, IDE)
# • Projects: Host D:\Projects\
# • Execution: Guest VM (Linux)
# • Shared folder: Mount D:\Projects\ -> /mnt/projects/
# -> Edit host, execute guest seamless!


# CONFIGURATION SHARED FOLDERS:
# ════════════════════════════

# WORKSTATION SETUP:
# ─────────────────

# 1. VM Settings -> Options -> Shared Folders
# 2. Folder sharing: Always enabled
# 
# Options:
# [FISHEYE] Always enabled (recommended dev)
# [WHITE_CIRCLE] Disabled until next power on
# [WHITE_CIRCLE] Disabled

# 3. [Add...] -> Add Shared Folder Wizard:
# 
# ┌──────────────────────────────────────────────┐
# │ Add Shared Folder Wizard                     │
# ├──────────────────────────────────────────────┤
# │ Host Path:                                   │
# │ [D:\Projects\WebApp\                  ]   │
# │                            [Browse...]       │
# │                                              │
# │ Name:                                        │
# │ [webapp-project                       ]   │
# │ (This name appears in guest VM)              │
# │                                              │
# │ Attributes:                                  │
# │ [x] Enable this share                         │
# │ [ ] Read-only                                 │
# │   (Guest can only read, not modify)          │
# │                                              │
# │          [Next >]          [Cancel]          │
# └──────────────────────────────────────────────┘

# Multiple shares:
# ───────────────
# Shared Folders:
# • webapp-project -> D:\Projects\WebApp\
# • datasets -> D:\Data\ML-Datasets\
# • documents -> C:\Users\John\Documents\


# LINUX GUEST ACCESS:
# ══════════════════

# VMHGFS-FUSE (Modern method):
# ───────────────────────────

# Install required packages:
# $ sudo apt install -y open-vm-tools-desktop

# Create mount point:
# $ sudo mkdir -p /mnt/hgfs

# Mount all shared folders:
# $ sudo mount -t fuse.vmhgfs-fuse .host:/ /mnt/hgfs -o allow_other

# List shared folders:
# $ ls -la /mnt/hgfs/
# drwxrwxrwx  2 root root  0 Dec 16 10:30 webapp-project
# drwxrwxrwx  2 root root  0 Dec 16 10:30 datasets
# drwxrwxrwx  2 root root  0 Dec 16 10:30 documents

# Access specific folder:
# $ cd /mnt/hgfs/webapp-project/
# $ ls -la
# -rw-rw-rw-  1 root root  1234 Dec 16 10:00 index.html
# -rw-rw-rw-  1 root root  5678 Dec 16 10:15 app.js


# AUTO-MOUNT AT BOOT:
# ══════════════════

# /etc/fstab entry:
# ────────────────
# $ sudo nano /etc/fstab
# 
# # VMware Shared Folders
# .host:/  /mnt/hgfs  fuse.vmhgfs-fuse  allow_other,defaults  0  0

# Create mount point:
# $ sudo mkdir -p /mnt/hgfs

# Test mount:
# $ sudo mount -a
# $ df -h | grep hgfs
# .host:/         466G  125G  341G  27% /mnt/hgfs


# SYSTEMD AUTO-MOUNT (Alternative):
# ═════════════════════════════════

# Create unit file:
# $ sudo nano /etc/systemd/system/mnt-hgfs.mount
# 
# [Unit]
# Description=VMware Shared Folders
# After=vmtoolsd.service
# Requires=vmtoolsd.service
# 
# [Mount]
# What=.host:/
# Where=/mnt/hgfs
# Type=fuse.vmhgfs-fuse
# Options=allow_other,defaults
# 
# [Install]
# WantedBy=multi-user.target

# Enable auto-mount:
# $ sudo systemctl daemon-reload
# $ sudo systemctl enable mnt-hgfs.mount
# $ sudo systemctl start mnt-hgfs.mount

# Verify:
# $ systemctl status mnt-hgfs.mount
# [BLACK_CIRCLE] mnt-hgfs.mount - VMware Shared Folders
#    Loaded: loaded
#    Active: active (mounted)
#     Where: /mnt/hgfs


# INDIVIDUAL FOLDER MOUNT:
# ═══════════════════════

# Mount specific shared folder:
# $ sudo mkdir -p /mnt/webapp
# $ sudo vmhgfs-fuse .host:/webapp-project /mnt/webapp -o allow_other

# Specific folder fstab:
# $ sudo nano /etc/fstab
# .host:/webapp-project  /mnt/webapp  fuse.vmhgfs-fuse  allow_other  0  0


# WINDOWS GUEST ACCESS:
# ════════════════════

# Automatic mapping:
# ─────────────────
# After VMware Tools install:
# • Shared folders appear network drives
# • Explorer -> Network Locations -> VMware Shared Folders
# • Path: \\vmware-host\Shared Folders\

# Map network drive:
# ─────────────────
# 1. Right-click "This PC" -> Map network drive
# 2. Drive: Z:
# 3. Folder: \\vmware-host\Shared Folders\webapp-project
# 4. [x] Reconnect at sign-in
# 5. [Finish]

# Access from command line:
# $ cd Z:\
# $ dir


# PERFORMANCE CONSIDERATIONS:
# ══════════════════════════

# Shared folders performance:
# ──────────────────────────
# • Small files: Excellent (native-like)
# • Large files: Good (slight overhead vs native)
# • Many small files: [WHITE_UP-POINTING_TRIANGLE] Slower (network overhead)
# • Database files: [X] NOT recommended
# • Compilation: [WHITE_UP-POINTING_TRIANGLE] Acceptable but slower

# Best practices:
# ──────────────
# [OK] Source code: Perfect use case
# [OK] Documents: Excellent
# [OK] Small datasets: Good
# [WHITE_UP-POINTING_TRIANGLE] Large transfers: Consider alternatives
# [X] Database files: Use virtual disk
# [X] Intensive I/O: Use virtual disk

# Alternatives large transfers:
# • SCP/SFTP: Better large files
# • Shared virtual disk: Better databases
# • NFS/SMB: Better multiple VMs


# SECURITY SHARED FOLDERS:
# ═══════════════════════

# Risks:
# • Guest malware access host files
# • Data exfiltration
# • Accidental host file deletion

# Mitigations:
# ──────────
# [OK] Read-only when possible
# [OK] Limit shared paths (specific folders)
# [OK] Disable if not needed
# [OK] Separate user accounts
# [OK] Regular backups host files

# Production:
# [ ] Disable shared folders (use network shares)


# ═══ 8.5 TROUBLESHOOTING VMWARE TOOLS ═══

# Problème: "VMware Tools not installed"
# ─────────────────────────────────────

# Symptôme:
# • Workstation status: "VMware Tools: Not installed"
# • Résolution fixe 800x600
# • Souris capturée

# Diagnostic Linux:
# $ systemctl status vmtoolsd
# Unit vmtoolsd.service could not be found.
# -> VMware Tools NOT installed

# Solution:
# $ sudo apt install -y open-vm-tools open-vm-tools-desktop
# $ sudo systemctl start vmtoolsd


# Problème: "VMware Tools outdated"
# ─────────────────────────────────

# Warning: "VMware Tools is out of date"

# Linux update:
# $ sudo apt update
# $ sudo apt upgrade open-vm-tools open-vm-tools-desktop

# Check version:
# $ vmware-toolbox-cmd -v
# 12.3.5.12345 (build-12345)


# Problème: "Shared folders not mounting"
# ──────────────────────────────────────

# Symptôme:
# $ ls /mnt/hgfs/
# ls: cannot access '/mnt/hgfs/': No such file or directory

# Diagnostic:
# $ systemctl status vmtoolsd
# Active: active (running)  <- Service OK
# 
# $ lsmod | grep vmhgfs
# [empty]  <- Module not loaded!

# Solution 1: Manual mount
# $ sudo mkdir -p /mnt/hgfs
# $ sudo mount -t fuse.vmhgfs-fuse .host:/ /mnt/hgfs -o allow_other

# Solution 2: Install desktop package
# $ sudo apt install -y open-vm-tools-desktop

# Solution 3: Check VM settings
# VM -> Settings -> Options -> Shared Folders
# -> Verify "Always enabled"
# -> Verify folders listed


# Problème: "Clipboard not working"
# ────────────────────────────────

# Symptôme:
# • Copy host -> paste guest: Nothing
# • Copy guest -> paste host: Nothing

# Diagnostic:
# VM -> Settings -> Options -> Guest Isolation
# Check status:
# [x] Enable copy and paste  <- Doit être checked

# Linux specific:
# $ pgrep vmtoolsd
# 1234  <- Process running
# 
# Si absent:
# $ sudo systemctl restart vmtoolsd

# Desktop environment required:
# • Clipboard nécessite GUI environment
# • Server sans GUI: Clipboard unavailable


# Problème: "Time drift persists"
# ──────────────────────────────

# Symptôme:
# $ date  # Guest
# Mon Dec 16 10:00:00 UTC 2024
# 
# Host clock: 10:30 (30 min drift!)

# Diagnostic:
# $ vmware-toolbox-cmd timesync status
# Disabled  <- Time sync désactivé!

# Solution:
# $ sudo vmware-toolbox-cmd timesync enable
# Enabled
# 
# $ sudo vmware-toolbox-cmd timesync resync
# 
# $ date
# Mon Dec 16 10:30:15 UTC 2024  <- Synchronisé!


# Problème: "Drag and drop not working"
# ─────────────────────────────────────

# Vérifications:
# ─────────────
# 1. VM Settings -> Guest Isolation
#    [x] Enable drag and drop

# 2. VMware Tools version:
#    $ vmware-toolbox-cmd -v
#    -> Update si obsolète

# 3. Desktop environment:
#    • Nécessite GUI (X11/Wayland)
#    • Server CLI: Drag&drop unavailable

# 4. File permissions:
#    • Check ~/Downloads/ writable


# Problème: "High CPU usage vmtoolsd"
# ──────────────────────────────────

# Symptôme:
# $ top
# PID    COMMAND      %CPU
# 1234   vmtoolsd     95.0  <- Abnormal!

# Causes possibles:
# • Shared folders intensive I/O
# • Clipboard sync loops
# • Time sync issues

# Solutions:
# 1. Restart service:
#    $ sudo systemctl restart vmtoolsd

# 2. Disable features temporarily:
#    $ vmware-toolbox-cmd timesync disable
#    $ sudo umount /mnt/hgfs  # Disable shared folders

# 3. Check logs:
#    $ journalctl -u vmtoolsd -n 100


# LOGS DIAGNOSTIC:
# ═══════════════

# Linux logs:
# ──────────
# $ journalctl -u vmtoolsd
# $ tail -f /var/log/vmware-vmsvc-root.log
# $ tail -f /var/log/vmware-vmtoolsd-root.log

# Windows logs:
# ────────────
# Event Viewer -> Applications and Services Logs -> VMware
# Files:
# C:\ProgramData\VMware\VMware Tools\logs\


# REINSTALLATION COMPLÈTE:
# ═══════════════════════

# Linux (si corruption):
# ─────────────────────
# $ sudo apt remove --purge open-vm-tools open-vm-tools-desktop
# $ sudo apt autoremove
# $ sudo apt clean
# $ sudo reboot
# 
# After reboot:
# $ sudo apt update
# $ sudo apt install -y open-vm-tools open-vm-tools-desktop
# $ sudo systemctl enable vmtoolsd
# $ sudo systemctl start vmtoolsd


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 8: VMWARE TOOLS - INSTALLATION ET UTILISATION
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# PARTIE 9: GESTION DU STOCKAGE VIRTUEL
# ═══════════════════════════════════════════════════════════════════


# ═══ 9.1 COMPRENDRE LE STOCKAGE VIRTUEL ═══

# TYPES DE DISQUES VIRTUELS:
# ═══════════════════════════

# 1. THIN PROVISIONED (Provisionné dynamique)
#    ────────────────────────────────────────
#    Caractéristiques:
#    • Taille initiale: Très petite (~500MB pour 100GB disk)
#    • Croissance: Dynamique selon utilisation
#    • Espace hôte: Utilisé au fur et à mesure
#    • Performance: Légèrement réduite (overhead allocation)
#    
#    Avantages:
#    [OK] Économie espace disque (utilise que nécessaire)
#    [OK] Déploiement rapide (création instantanée)
#    [OK] Over-provisioning possible (10 VMs × 100GB sur 500GB)
#    
#    Inconvénients:
#    [X] Fragmentation possible
#    [X] Risque saturation hôte (si growth non surveillé)
#    [X] Performance inférieure thick

# 2. THICK PROVISIONED LAZY ZEROED
#    ──────────────────────────────
#    • Espace alloué immédiatement
#    • Zéros écrits à la demande (lazy)
#    • Création rapide
#    • Performance bonne

# 3. THICK PROVISIONED EAGER ZEROED
#    ───────────────────────────────
#    • Espace alloué + rempli zéros immédiatement
#    • Création lente (peut prendre heures)
#    • Performance maximale
#    • Sécurité maximale (données précédentes effacées)
#    • Use case: Databases production, VMs critiques

# Comparaison création disk 100GB:
# ─────────────────────────────────
# Type              | Taille | Temps  | Performance
# ──────────────────┼────────┼────────┼────────────
# Thin              | 500MB  | 10s    | [WHITE_UP-POINTING_TRIANGLE] (90%)
# Thick Lazy        | 100GB  | 30s    | [WHITE_CIRCLE] (95%)
# Thick Eager       | 100GB  | 15min  | [OK] (100%)


# EXPAND VIRTUAL DISK:
# ════════════════════

# QUAND agrandir disk?
# ───────────────────
# • VM manque espace (df -h: 95% used)
# • Application nécessite plus stockage
# • Logs remplissent partition
# • Nouvelle fonctionnalité nécessite data

# COMMENT agrandir:
# ────────────────

# ÉTAPE 1: Agrandir disk VMware
# ─────────────────────────────
# 1. Power off VM (OBLIGATOIRE)
# 2. VM -> Settings -> Hard Disk
# 3. Utilities -> Expand
# 
# ┌──────────────────────────────────────────────┐
# │ Expand Disk Capacity                         │
# ├──────────────────────────────────────────────┤
# │ Current size: 20 GB                          │
# │                                              │
# │ New size (GB):                               │
# │ [30                                    ]  │
# │                                              │
# │ [ATTENTION] VM must be powered off                    │
# │ [ATTENTION] Cannot shrink disk (only expand)          │
# │ [ATTENTION] Backup recommended before expanding       │
# │                                              │
# │          [Expand]          [Cancel]          │
# └──────────────────────────────────────────────┘

# ÉTAPE 2: Étendre partition guest
# ────────────────────────────────
# Disk agrandi mais partition pas encore!

# Linux (Ubuntu):
# $ lsblk
# NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
# sda      8:0    0   30G  0 disk          <- Disk 30GB
# ├─sda1   8:1    0    1M  0 part
# ├─sda2   8:2    0  1.8G  0 part /boot
# └─sda3   8:3    0 18.2G  0 part /        <- Partition seulement 18GB!
# 
# Espace non alloué: 30GB - 20GB = 10GB disponible

# Étendre partition LVM:
# $ sudo lvextend -l +100%FREE /dev/mapper/ubuntu--vg-ubuntu--lv
# $ sudo resize2fs /dev/mapper/ubuntu--vg-ubuntu--lv
# 
# Vérifier:
# $ df -h /
# Filesystem                         Size  Used Avail Use% Mounted on
# /dev/mapper/ubuntu--vg-ubuntu--lv   28G   15G   13G  54% /
# [OK] Partition étendue 28GB!

# Étendre partition non-LVM:
# $ sudo apt install -y cloud-guest-utils
# $ sudo growpart /dev/sda 3
# $ sudo resize2fs /dev/sda3


# ADD ADDITIONAL DISK:
# ═══════════════════

# QUAND ajouter disk séparé?
# ─────────────────────────
# • Séparer OS et données
# • Database sur disk dédié
# • Logs sur disk séparé
# • Performance (I/O parallèle)

# COMMENT:
# ───────
# 1. VM Settings -> [Add...] -> Hard Disk
# 2. Wizard: Create new virtual disk
# 3. Disk type: SCSI (recommended) / SATA / NVMe
# 4. Size: 50GB
# 5. Provisioning: Thin / Thick
# 6. [Finish]

# Linux: Format et mount nouveau disk
# ───────────────────────────────────
# Identifier nouveau disk:
# $ lsblk
# NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
# sda      8:0    0   30G  0 disk
# └─sda1   8:1    0   30G  0 part /
# sdb      8:16   0   50G  0 disk          <- Nouveau disk!

# Partitionner:
# $ sudo parted /dev/sdb mklabel gpt
# $ sudo parted /dev/sdb mkpart primary ext4 0% 100%

# Formater:
# $ sudo mkfs.ext4 /dev/sdb1

# Mount temporaire:
# $ sudo mkdir -p /data
# $ sudo mount /dev/sdb1 /data

# Auto-mount boot (fstab):
# $ sudo blkid /dev/sdb1
# /dev/sdb1: UUID="abc123..." TYPE="ext4"
# 
# $ sudo nano /etc/fstab
# UUID=abc123... /data ext4 defaults 0 2
# 
# $ sudo systemctl daemon-reload
# $ sudo mount -a


# ═══ 9.2 DISK MODES ═══

# PERSISTENT MODE (Défaut):
# ════════════════════════
# • Changements sauvegardés
# • Writes permanents disk
# • Mode normal production

# INDEPENDENT MODES:
# ═════════════════

# 1. INDEPENDENT PERSISTENT
#    ──────────────────────
#    • Changements sauvegardés
#    • Mais exclu snapshots!
#    • Use case: Logs, swap, temp data

# 2. INDEPENDENT NONPERSISTENT
#    ─────────────────────────
#    • Changements PERDUS à power off!
#    • Disk reset état original chaque boot
#    • Use case: Kiosks, test environments

# Configuration:
# VM -> Settings -> Hard Disk -> Advanced
# Mode:
# [FISHEYE] Dependent (normal)
# [WHITE_CIRCLE] Independent - Persistent
# [WHITE_CIRCLE] Independent - Nonpersistent


# ═══ 9.3 DISK MAINTENANCE ═══

# DEFRAGMENT VIRTUAL DISK:
# ════════════════════════

# QUAND defragmenter?
# ──────────────────
# • Après nombreuses écritures/suppressions
# • Performance disk dégradée
# • Fragmentation élevée

# COMMENT:
# ───────
# 1. Inside guest: Defrag filesystem
#    Linux: Generally pas nécessaire (ext4 auto-defrag)
#    Windows: Défragmenteur Windows
# 
# 2. VMware level: Defrag VMDK
#    $ vmware-vdiskmanager -d "/path/to/disk.vmdk"


# COMPACT VIRTUAL DISK:
# ════════════════════

# Récupérer espace inutilisé:
# ──────────────────────────

# Thin provisioned disk:
# • Guest utilise 30GB
# • Delete 10GB fichiers
# • Disk VMDK reste 30GB! (pas shrink auto)

# Solution: Compact disk
# ─────────────────────

# Linux guest preparation:
# $ sudo apt install -y zerofree
# 
# Boot single-user ou LiveCD:
# $ sudo zerofree /dev/sda1
# OU
# $ sudo dd if=/dev/zero of=/fillfile bs=1M
# $ sudo rm /fillfile

# VMware compact:
# VM -> Settings -> Hard Disk -> Utilities -> Compact
# 
# OU CLI:
# $ vmware-vdiskmanager -k "/path/to/disk.vmdk"


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 9: GESTION DU STOCKAGE VIRTUEL
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# PARTIE 10: PERFORMANCE ET OPTIMISATION VM
# ═══════════════════════════════════════════════════════════════════


# ═══ 10.1 CPU ALLOCATION ═══

# RÈGLES ALLOCATION vCPU:
# ══════════════════════

# Best Practice: 1:1 ratio (idéal)
# • 1 vCPU = 1 physical core
# • Performance optimale
# • Pas contention

# Acceptable: 2:1 ratio
# • 2 vCPUs = 1 physical core
# • Légère contention possible
# • Workloads pas CPU-intensive

# Maximum: 4:1 ratio
# • 4 vCPUs = 1 physical core
# • Contention probable
# • Performance dégradée
# • Seulement workloads légers

# Exemple host 8 cores:
# ────────────────────
# Optimal:
# • 8 VMs × 1 vCPU = 8 vCPUs total (ratio 1:1)

# Acceptable:
# • 4 VMs × 2 vCPUs = 8 vCPUs total (ratio 1:1)
# • OU 8 VMs × 2 vCPUs = 16 vCPUs total (ratio 2:1)

# Dangereux:
# • 8 VMs × 8 vCPUs = 64 vCPUs total (ratio 8:1)
# -> Performance catastrophique!


# CONFIGURATION vCPU:
# ══════════════════

# VM Settings -> Hardware -> Processors
# 
# Number of processors: [2]
# Number of cores per processor: [2]
# -> Total vCPUs: 2 × 2 = 4 vCPUs

# Préférence:
# • 1 processor × 4 cores (moderne)
# • vs 4 processors × 1 core (ancien)
# -> Performance identique, licensing différent


# HYPERTHREADING CONSIDERATION:
# ═════════════════════════════

# Host 8 cores with HT = 16 logical processors
# 
# Conservative:
# • Count physical cores only (8)
# • Allocate based 8 cores

# Aggressive:
# • Count logical processors (16)
# • Allocate based 16
# • Acceptable si workloads variés


# CPU RESERVATION & LIMITS:
# ═════════════════════════

# VM Settings -> Options -> Advanced -> Processor
# 
# Reservation:
# • Guaranteed minimum MHz
# • Use case: Critical VMs
# • Example: Reserve 2000 MHz
# 
# Limit:
# • Maximum MHz VM can use
# • Use case: Prevent VM monopolizing
# • Example: Limit 4000 MHz
# 
# Shares:
# • Priority relative autres VMs
# • Low / Normal / High / Custom


# ═══ 10.2 MEMORY ALLOCATION ═══

# SIZING MEMORY:
# ═════════════

# Formula:
# Total RAM = RAM OS + RAM Applications + Overhead

# Linux server examples:
# ─────────────────────
# Web server (Apache/Nginx):
# • OS: 512MB
# • Apache: 1-2GB
# • PHP workers: 1-2GB
# • Total: 4GB recommended

# Database server (MySQL):
# • OS: 1GB
# • MySQL buffer pool: 70% RAM available
# • Total: 8-16GB minimum

# Application server:
# • OS: 1GB
# • App: Variable (Java heap, etc)
# • Total: Depends workload


# MEMORY RESERVATION:
# ══════════════════

# Reserve memory garantit VM:
# ──────────────────────────
# • RAM toujours disponible
# • Pas swapping host
# • Performance prévisible

# Configuration:
# VM Settings -> Options -> Advanced -> Memory
# Reservation: [4096] MB (garantis)

# Warning: Reserved memory = locked host RAM
# • 5 VMs × 4GB reserved = 20GB host locked
# • Limit réservations total < 50% host RAM


# MEMORY OVERHEAD:
# ═══════════════

# VMware overhead per VM:
# ──────────────────────
# • VM 1GB RAM: +50-100MB overhead
# • VM 8GB RAM: +200-400MB overhead
# • VM 32GB RAM: +500MB-1GB overhead

# Total host memory calculation:
# ─────────────────────────────
# Host 32GB RAM:
# • Host OS: 8GB
# • VM overhead: 2GB (estimate)
# • Available VMs: 22GB
# -> 5 VMs × 4GB = 20GB (safe)


# MEMORY BALLOONING:
# ═════════════════

# VMware Balloon driver:
# • Inside guest (vmware_balloon)
# • Reclaims unused RAM
# • Pas performance impact si bien géré

# Check balloon activity:
# $ cat /proc/meminfo | grep -i balloon
# VMallocTotal: 34359738367 kB
# VmallocUsed:  125924 kB

# Disable ballooning (si needed):
# VM Settings -> Options -> Advanced -> Memory
# [ ] Enable memory ballooning


# ═══ 10.3 DISK I/O OPTIMIZATION ═══

# STORAGE CONTROLLER TYPE:
# ═══════════════════════

# Types disponibles:
# ─────────────────

# 1. LSI Logic SAS (Défaut moderne)
#    • Bon équilibre performance/compatibilité
#    • Recommandé general purpose
#    • Support toutes OS récents

# 2. PVSCSI (Paravirtualized SCSI)
#    • Performance maximale
#    • Nécessite VMware Tools
#    • Use case: I/O intensive (databases)
#    • Requires driver installation OS

# 3. NVMe
#    • Émulation SSD NVMe
#    • Performance excellente
#    • Requires modern OS (Linux 4.x+)
#    • Recommandé VMs récents

# 4. IDE (Legacy)
#    • Ancien, lent
#    • Éviter sauf ancien OS

# Performance comparison:
# ──────────────────────
# IDE: 100MB/s
# LSI Logic SAS: 300MB/s
# PVSCSI: 500MB/s
# NVMe: 1000MB/s+


# DISK PLACEMENT:
# ══════════════

# Best practices:
# ──────────────
# [OK] VMs sur SSD (vs HDD): +300% performance
# [OK] Separate disks: OS + Data different disks
# [OK] RAID configuration: RAID10 optimal
# [X] Avoid: Multiple VMs même disk (contention)


# ═══ 10.4 NETWORK OPTIMIZATION ═══

# NETWORK ADAPTER TYPE:
# ════════════════════

# 1. E1000 (Legacy)
#    • Émulation Intel 82545EM
#    • Compatible universel
#    • Performance: ~1Gbps
#    • Use case: Compatibilité anciens OS

# 2. E1000E (Enhanced)
#    • Émulation Intel 82574
#    • Better performance
#    • ~2Gbps

# 3. VMXNET3 (Paravirtualized) [OK] RECOMMANDÉ
#    • Performance optimale
#    • ~10Gbps capable
#    • Nécessite VMware Tools
#    • Use case: Production, performance critique

# Configuration:
# VM -> Settings -> Network Adapter -> Advanced
# Adapter type:
# [FISHEYE] VMXNET3 (recommended)

# Performance comparison:
# ──────────────────────
# E1000: 1 Gbps max
# VMXNET3: 10 Gbps capable
# -> 10x throughput potentiel!


# ═══ 10.5 GRAPHICS OPTIMIZATION ═══

# 3D ACCELERATION:
# ═══════════════

# Enable 3D graphics:
# VM -> Settings -> Display
# [x] Accelerate 3D graphics
# 
# 3D memory: [512] MB (max 2GB)

# Use cases:
# • Desktop Linux/Windows graphique
# • CAD applications
# • Development IDEs
# • Video rendering

# Server without GUI:
# [ ] Disable 3D (économise RAM)


# ═══ 10.6 MONITORING PERFORMANCE ═══

# WORKSTATION STATS:
# ═════════════════

# View -> Performance Monitor
# 
# Metrics:
# • CPU Usage (%)
# • Memory Usage (%)
# • Disk I/O (MB/s)
# • Network I/O (Mbps)

# Graphs real-time:
# ┌─────────────────────────────────┐
# │ Performance                     │
# │                                 │
# │ CPU: [████████░░] 82%           │
# │ RAM: [██████░░░░] 65%           │
# │ Disk: 45 MB/s read              │
# │       12 MB/s write             │
# │ Network: 125 Mbps               │
# └─────────────────────────────────┘


# GUEST OS MONITORING:
# ═══════════════════

# Linux tools:
# ───────────
# $ top              # CPU/Memory overview
# $ htop             # Enhanced top
# $ iotop            # Disk I/O
# $ iftop            # Network traffic
# $ vmstat 1         # VM statistics
# $ iostat -x 1      # I/O statistics

# Performance baseline:
# $ vmstat 1 10
# procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
#  r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
#  1  0      0 123456  78901 234567    0    0    10    20  100  200  5  2 90  3  0


# ═══ 10.7 TROUBLESHOOTING PERFORMANCE ═══

# VM LENTE - DIAGNOSTIC:
# ═════════════════════

# 1. CHECK CPU USAGE
#    ──────────────
# Workstation Performance Monitor: CPU > 90%
# -> CPU bottleneck
# 
# Solutions:
# • Add vCPUs (si host cores disponibles)
# • Optimize applications
# • Distribute load

# 2. CHECK MEMORY
#    ───────────
# Inside guest:
# $ free -h
#               total        used        free      shared  buff/cache   available
# Mem:           4.0G        3.8G        100M         50M        150M        100M
#                                         ^ Low!
# 
# Swap usage high -> Memory pressure
# 
# Solutions:
# • Increase VM RAM
# • Optimize applications
# • Close services

# 3. CHECK DISK I/O
#    ─────────────
# $ iostat -x 1
# Device  r/s    w/s    rMB/s    wMB/s    %util
# sda     500    200    50.0     20.0     98      <- Saturated!
# 
# Solutions:
# • Upgrade HDD -> SSD
# • Change controller PVSCSI/NVMe
# • Add disk separate I/O
# • RAID optimization

# 4. CHECK NETWORK
#    ────────────
# $ iftop
# Bandwidth: 950Mbps <- Near 1Gbps limit
# 
# Solutions:
# • Upgrade adapter VMXNET3
# • Add second NIC
# • QoS configuration


# READY-TO-RUN QUEUE:
# ══════════════════

# VMware metric: CPU Ready
# • Time VM waited CPU available
# • High ready = CPU contention
# • Ideal: < 5%
# • Warning: > 10%
# • Critical: > 20%

# Check:
# esxtop (ESXi)
# OU
# Workstation: Performance charts


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 10: PERFORMANCE ET OPTIMISATION VM
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# PARTIE 11: SÉCURITÉ VMWARE
# ═══════════════════════════════════════════════════════════════════


# ═══ 11.1 ENCRYPTION VM ═══

# POURQUOI chiffrer VMs?
# ═════════════════════

# Risques VM non chiffrée:
# • Vol disque/laptop -> Accès fichiers .vmdk
# • Backup volé -> Données exposées
# • Insider threat -> Admin malveillant copy VMs
# • Compliance requirements -> RGPD, HIPAA, PCI-DSS

# Encryption protects:
# • .vmdk files (disques)
# • .vmem files (mémoire)
# • .vmx files (config)
# • .nvram files (BIOS)
# • Snapshots


# ENCRYPTION WORKSTATION:
# ══════════════════════

# Workstation Pro uniquement (pas Player)

# Enable encryption:
# ─────────────────
# VM -> Settings -> Options -> Access Control
# [x] Encrypt this virtual machine
# 
# Password setup:
# ┌──────────────────────────────────────────────┐
# │ Encrypt Virtual Machine                      │
# ├──────────────────────────────────────────────┤
# │ Enter password to encrypt VM:                │
# │                                              │
# │ Password: [********************]          │
# │ Confirm:  [********************]          │
# │                                              │
# │ [ATTENTION] IMPORTANT:                                │
# │ • Store password securely                    │
# │ • Lost password = VM inaccessible forever    │
# │ • No recovery method exists                  │
# │                                              │
# │          [Encrypt]          [Cancel]         │
# └──────────────────────────────────────────────┘

# Encryption process:
# • VM powered off
# • Files encrypted AES-256
# • Durée: 5-30 minutes (selon taille)


# UTILISATION VM CHIFFRÉE:
# ═══════════════════════

# Power on:
# ┌──────────────────────────────────────────────┐
# │ Enter Password                               │
# ├──────────────────────────────────────────────┤
# │ VM "Ubuntu-Server" is encrypted.             │
# │                                              │
# │ Password: [********************]          │
# │                                              │
# │ [ ] Remember password for this session        │
# │                                              │
# │          [OK]          [Cancel]              │
# └──────────────────────────────────────────────┘

# Remember password:
# • Checked: Password cached session
# • Unchecked: Demandé chaque power on


# CHANGE ENCRYPTION PASSWORD:
# ══════════════════════════

# VM -> Settings -> Options -> Access Control
# [Change Password...]
# 
# • Old password
# • New password
# • Confirm


# REMOVE ENCRYPTION:
# ═════════════════

# VM -> Settings -> Options -> Access Control
# [ ] Encrypt this virtual machine
# -> Enter password -> Decrypt

# Note: Decryption irréversible!


# ═══ 11.2 ISOLATION GUEST ═══

# GUEST ISOLATION SETTINGS:
# ════════════════════════

# VM -> Settings -> Options -> Guest Isolation
# 
# Security features:
# [ ] Enable copy and paste (défaut: checked)
# [ ] Enable drag and drop (défaut: checked)

# Security recommendation:
# Production VMs sensibles:
# [x] Désactiver copy/paste (prevent exfiltration)
# [x] Désactiver drag/drop


# ═══ 11.3 USB DEVICE SECURITY ═══

# USB POLICIES:
# ════════════

# VM -> Settings -> USB Controller
# 
# Options:
# [WHITE_CIRCLE] Show all USB input devices (défaut)
# [WHITE_CIRCLE] Share Bluetooth devices with VM
# [WHITE_CIRCLE] Automatically connect new USB devices

# Secure configuration production:
# • Disable automatic connection
# • Whitelist specific devices only
# • No USB mass storage


# ═══ 11.4 NETWORK SECURITY ═══

# NETWORK ISOLATION:
# ═════════════════

# Host-Only network for isolation:
# • VMs communicate entre elles
# • Pas Internet access
# • Isolated du host LAN
# • Use case: Malware analysis, labs


# FIREWALL VM:
# ═══════════

# Linux (UFW):
# ───────────
# $ sudo ufw status
# Status: inactive
# 
# $ sudo ufw default deny incoming
# $ sudo ufw default allow outgoing
# $ sudo ufw allow ssh
# $ sudo ufw allow 80/tcp
# $ sudo ufw allow 443/tcp
# $ sudo ufw enable

# Verify:
# $ sudo ufw status numbered
# Status: active
# 
#      To                         Action      From
#      --                         ------      ----
# [ 1] 22/tcp                     ALLOW IN    Anywhere
# [ 2] 80/tcp                     ALLOW IN    Anywhere
# [ 3] 443/tcp                    ALLOW IN    Anywhere


# ═══ 11.5 SECURE BOOT ═══

# UEFI SECURE BOOT:
# ════════════════

# Enable Secure Boot:
# VM -> Settings -> Options -> Advanced
# Firmware type: UEFI
# [x] Enable UEFI Secure Boot

# Requirements:
# • OS support Secure Boot (Windows 8+, Ubuntu 16.04+)
# • UEFI firmware (pas BIOS)

# Benefits:
# • Prevent unauthorized bootloaders
# • Protection rootkits
# • Boot-level malware protection


# ═══ 11.6 SECURITY BEST PRACTICES ═══

# CHECKLIST SÉCURITÉ VM:
# ═════════════════════

# [OK] Minimiser surfaces attack:
#   • Désactiver services inutilisés
#   • Fermer ports non nécessaires
#   • Remove unnecessary packages

# [OK] Updates réguliers:
#   • OS patches monthly
#   • VMware Tools updated
#   • Applications patched

# [OK] Strong authentication:
#   • SSH keys (disable password)
#   • Strong passwords (12+ chars)
#   • Sudo au lieu root direct

# [OK] Monitoring & logging:
#   • Enable syslog
#   • Central log collection
#   • Alerting failed logins

# [OK] Encryption:
#   • Encrypt sensitive VMs
#   • Encrypt backups
#   • Encrypted connections (SSH, HTTPS)

# [OK] Access control:
#   • Least privilege principle
#   • Separate accounts admin/user
#   • Regular access review


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 11: SÉCURITÉ VMWARE
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# PARTIE 12: BACKUP ET DISASTER RECOVERY
# ═══════════════════════════════════════════════════════════════════


# ═══ 12.1 STRATÉGIES BACKUP ═══

# POURQUOI backup VMs?
# ═══════════════════

# Scénarios disaster:
# • Hardware failure -> Disque host meurt
# • Corruption filesystem -> VM unbootable
# • Ransomware attack -> Files encrypted
# • Human error -> Accidental deletion
# • Disaster naturel -> Datacenter détruit

# Sans backup:
# [X] VM perdue définitivement
# [X] Données irrécupérables
# [X] Business downtime prolongé
# [X] Coût récupération énorme

# Avec backup:
# [OK] Restore VM minutes/heures
# [OK] Zéro perte données (si backup récent)
# [OK] Business continuity maintenue
# [OK] Peace of mind


# BACKUP vs SNAPSHOTS:
# ═══════════════════

# SNAPSHOTS:
# • Fichiers sur MÊME storage VM
# • Protection erreurs config court-terme
# • Pas protection hardware failure
# • Durée vie: heures/jours
# • Impact performance
# • Use case: Tests, rollback rapide

# BACKUPS:
# • Copie EXTERNE (autre disque/serveur/cloud)
# • Protection disaster complet
# • Zéro impact performance production
# • Durée vie: jours/mois/années
# • Use case: DR, compliance, archives

# Complémentaires:
# • Snapshot avant change (rollback immediat)
# • Backup régulier (disaster recovery)


# RÈGLE 3-2-1 BACKUP:
# ══════════════════

# 3 copies données:
# • 1 production
# • 2 backups

# 2 medias différents:
# • Disque local
# • Cloud / Tape / NAS

# 1 copie off-site:
# • Autre location géographique
# • Protection disaster local

# Exemple:
# • Production: VM sur host
# • Backup 1: External USB drive
# • Backup 2: Cloud storage (AWS S3)


# ═══ 12.2 MÉTHODES BACKUP ═══

# MÉTHODE 1: COPY FICHIERS VM
# ═══════════════════════════

# Simple file copy:
# ────────────────

# 1. Power off VM (CRITIQUE!)
# 2. Copy dossier VM complet
# 3. Paste destination backup

# Linux:
# $ sudo rsync -avh --progress \
#     /home/user/VMs/Ubuntu-Server/ \
#     /backup/VMs/Ubuntu-Server-2024-12-16/

# Windows:
# > robocopy "D:\VMs\Ubuntu-Server" "E:\Backup\Ubuntu-Server-2024-12-16" /MIR

# Avantages:
# [OK] Simple, pas outils spéciaux
# [OK] Restore rapide (copy back)
# [OK] Portable entre hosts

# Inconvénients:
# [X] VM doit être powered off
# [X] Pas incremental (full backup chaque fois)
# [X] Temps long (20GB = 10-30 min)
# [X] Beaucoup espace disque


# MÉTHODE 2: VMWARE WORKSTATION BACKUP
# ════════════════════════════════════

# Export VM (OVF/OVA):
# ───────────────────

# File -> Export to OVF...
# 
# ┌──────────────────────────────────────────────┐
# │ Export to OVF                                │
# ├──────────────────────────────────────────────┤
# │ Source:                                      │
# │ Virtual machine: Ubuntu-Server               │
# │                                              │
# │ Destination:                                 │
# │ Directory: [E:\Backups\               ]   │
# │                            [Browse...]       │
# │                                              │
# │ Name: [Ubuntu-Server-Backup           ]   │
# │                                              │
# │ Format:                                      │
# │ [FISHEYE] OVF (multiple files)                       │
# │ [WHITE_CIRCLE] OVA (single archive file)                  │
# │                                              │
# │ Description: (Optional)                      │
# │ [Backup 2024-12-16 before kernel update]  │
# │                                              │
# │          [Export]          [Cancel]          │
# └──────────────────────────────────────────────┘

# OVF vs OVA:
# ──────────
# OVF (Open Virtualization Format):
# • Multiple files (.ovf + .vmdk + .mf)
# • Faster export
# • Easier modify
# • Standard VMware/VirtualBox/etc

# OVA (Open Virtualization Archive):
# • Single .ova file (tar archive)
# • Easier transfer
# • Slightly slower
# • More portable

# Export duration:
# • 20GB VM: 10-20 minutes
# • 100GB VM: 30-60 minutes


# RESTORE FROM OVF/OVA:
# ════════════════════

# File -> Open...
# -> Select .ovf OU .ova file
# -> Import wizard
# -> Restore completed


# MÉTHODE 3: INCREMENTAL BACKUP
# ═════════════════════════════

# Tools:
# • rsync with --link-dest
# • Duplicati
# • Veeam Backup (Free)
# • Acronis

# rsync incremental example:
# ─────────────────────────

# Backup script:
# #!/bin/bash
# DATE=$(date +%Y-%m-%d-%H%M)
# BACKUP_ROOT="/backup/VMs"
# VM_PATH="/home/user/VMs/Ubuntu-Server"
# 
# LATEST="$BACKUP_ROOT/Ubuntu-Server-latest"
# CURRENT="$BACKUP_ROOT/Ubuntu-Server-$DATE"
# 
# # Incremental backup (hard links unchanged files)
# rsync -avh --delete --link-dest="$LATEST" \
#     "$VM_PATH/" "$CURRENT/"
# 
# # Update latest symlink
# rm -f "$LATEST"
# ln -s "$CURRENT" "$LATEST"

# Structure:
# /backup/VMs/
# ├─ Ubuntu-Server-2024-12-14-1000/  (30GB)
# ├─ Ubuntu-Server-2024-12-15-1000/  (2GB changed)
# ├─ Ubuntu-Server-2024-12-16-1000/  (1GB changed)
# └─ Ubuntu-Server-latest -> 2024-12-16-1000/


# ═══ 12.3 AUTOMATED BACKUP ═══

# CRON SCHEDULE BACKUP:
# ════════════════════

# Daily backup 2AM:
# $ crontab -e
# 0 2 * * * /home/user/scripts/backup-vms.sh

# Weekly full + daily incremental:
# # Full backup Sunday 3AM
# 0 3 * * 0 /home/user/scripts/backup-vms-full.sh
# 
# # Incremental Monday-Saturday 3AM
# 0 3 * * 1-6 /home/user/scripts/backup-vms-incremental.sh


# BACKUP SCRIPT EXAMPLE:
# ═════════════════════

# File: backup-vms.sh
# ──────────────────
# #!/bin/bash
# 
# VM_NAME="Ubuntu-Server"
# VM_PATH="/home/user/VMs/$VM_NAME"
# BACKUP_PATH="/backup/VMs"
# DATE=$(date +%Y-%m-%d-%H%M)
# LOG="/var/log/vm-backup.log"
# 
# echo "[$DATE] Starting backup $VM_NAME" >> "$LOG"
# 
# # Power off VM gracefully
# vmrun -T ws stop "$VM_PATH/$VM_NAME.vmx" soft
# 
# # Wait shutdown
# sleep 30
# 
# # Backup
# rsync -avh --delete \
#     "$VM_PATH/" \
#     "$BACKUP_PATH/$VM_NAME-$DATE/" \
#     >> "$LOG" 2>&1
# 
# if [ $? -eq 0 ]; then
#     echo "[$DATE] Backup successful" >> "$LOG"
#     
#     # Cleanup old backups (keep 7 days)
#     find "$BACKUP_PATH" -name "$VM_NAME-*" -mtime +7 -exec rm -rf {} \;
#     
#     # Restart VM
#     vmrun -T ws start "$VM_PATH/$VM_NAME.vmx" nogui
# else
#     echo "[$DATE] Backup FAILED" >> "$LOG"
# fi


# ═══ 12.4 DISASTER RECOVERY ═══

# DR PLAN:
# ═══════

# 1. RECOVERY TIME OBJECTIVE (RTO)
#    ──────────────────────────────
#    • Maximum downtime acceptable
#    • Example: 4 hours
#    • Determines backup frequency

# 2. RECOVERY POINT OBJECTIVE (RPO)
#    ───────────────────────────────
#    • Maximum data loss acceptable
#    • Example: 24 hours
#    • Determines backup schedule

# Example scenarios:
# ─────────────────
# Critical production server:
# • RTO: 1 hour
# • RPO: 1 hour
# -> Backup every hour + hot standby

# Development VM:
# • RTO: 24 hours
# • RPO: 1 day
# -> Daily backup sufficient


# RESTORE PROCEDURE:
# ═════════════════

# Full VM restore:
# ───────────────

# 1. Identify backup restore point
# $ ls -l /backup/VMs/
# drwxr-xr-x 2024-12-14-1000  <- Trop ancien
# drwxr-xr-x 2024-12-15-1000  <- Avant incident
# drwxr-xr-x 2024-12-16-1000  <- Après incident (corrompu)

# 2. Restore backup
# $ rsync -avh --delete \
#     /backup/VMs/Ubuntu-Server-2024-12-15-1000/ \
#     /home/user/VMs/Ubuntu-Server/

# 3. Open VM Workstation
# File -> Open -> Ubuntu-Server.vmx

# 4. Power on
# VM -> Power -> Power On

# 5. Verify functionality
# • Boot successful
# • Services running
# • Data accessible
# • Network functional

# 6. Update recovery log
# • Time incident
# • Backup used
# • Time restore completed
# • Services verified


# RESTORE FICHIERS INDIVIDUELS:
# ═════════════════════════════

# Extract specific files from backup:
# ───────────────────────────────────

# 1. Mount backup VMDK (read-only)
# $ sudo mkdir -p /mnt/backup
# $ sudo vmware-mount /backup/VMs/Ubuntu-Server.vmdk 1 /mnt/backup

# 2. Copy fichiers nécessaires
# $ sudo cp /mnt/backup/etc/nginx/nginx.conf /tmp/recovered-nginx.conf

# 3. Unmount
# $ sudo vmware-mount -d /mnt/backup


# ═══ 12.5 BACKUP VALIDATION ═══

# TEST RESTORE RÉGULIER:
# ═════════════════════

# Best practice:
# • Test restore monthly minimum
# • Verify backup integrity
# • Document restore procedure
# • Measure restore time

# Test procedure:
# ──────────────
# 1. Schedule test (off-hours)
# 2. Create test environment
# 3. Restore backup vers test
# 4. Verify VM boots
# 5. Check services functional
# 6. Measure restore duration
# 7. Document results
# 8. Update DR plan si issues


# BACKUP MONITORING:
# ═════════════════

# Check points:
# ────────────
# [OK] Backup completed successfully
# [OK] Duration acceptable
# [OK] Size expected
# [OK] No errors logs
# [OK] Backup accessible
# [OK] Encryption functional (si enabled)

# Alerting script:
# ───────────────
# #!/bin/bash
# BACKUP_LOG="/var/log/vm-backup.log"
# 
# if grep -q "FAILED" "$BACKUP_LOG"; then
#     echo "VM Backup FAILED - Check logs" | \
#         mail -s "ALERT: VM Backup Failed" admin@company.com
# fi


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 12: BACKUP ET DISASTER RECOVERY
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# CONCLUSION ET RESSOURCES
# ═══════════════════════════════════════════════════════════════════

# Ce guide couvre les fondamentaux VMware Workstation pour
# administrateurs Linux/réseaux débutants. Les concepts et
# pratiques présentés forment une base solide pour:

# • Administration VMs quotidienne
# • Troubleshooting problèmes courants
# • Optimisation performance
# • Sécurité et backup
# • Progression vers environnements enterprise (ESXi/vSphere)

# PROCHAINES ÉTAPES:
# ═════════════════

# 1. PRATIQUE HANDS-ON
#    • Créer lab personnel
#    • Tester tous scénarios
#    • Expérimenter configurations

# 2. CERTIFICATIONS
#    • VMware Certified Associate (VCA)
#    • VMware Certified Professional (VCP)

# 3. ENVIRONNEMENTS AVANCÉS
#    • VMware ESXi (bare-metal)
#    • vCenter Server (management centralisé)
#    • vSphere features (HA, DRS, vMotion)

# 4. AUTOMATION
#    • PowerCLI (VMware PowerShell)
#    • Terraform VMware provider
#    • Ansible VMware modules

# RESSOURCES OFFICIELLES:
# ══════════════════════

# Documentation:
# • VMware Docs: https://docs.vmware.com
# • KB Articles: https://kb.vmware.com
# • Community Forums: https://communities.vmware.com

# Formation:
# • VMware Learning Zone
# • VMware Hands-on Labs (gratuit)
# • YouTube VMware Official Channel

# Support:
# • VMware Support Portal
# • Community assistance
# • Professional services

# ═══════════════════════════════════════════════════════════════════
# FIN DU GUIDE VMWARE ULTRA-DÉTAILLÉ
# ═══════════════════════════════════════════════════════════════════