#!/usr/bin/env python3
"""Génère une arborescence de fichiers leurres ultra-réalistes pour la VM honeypot.

Produit :
  - /srv/samba/comptabilite/Archives/{2020,2021,2022,2023,2024,2025,2026}/{mois}/<fichiers>
  - /srv/samba/informatique/{Réseau,Postes,Comptes-Admin,Sauvegardes}/<fichiers>
  - /srv/samba/RH/{Contrats,Paie,Recrutement}/<fichiers>
  - /srv/samba/Direction/<docs sensibles bidons>

Tous les fichiers sont VALIDES (s'ouvrent dans Excel/Word/PDF) avec contenu
réaliste mais 100% inventé. Numéros SIRET / IBAN / NIR au format français
mais sans correspondance réelle.

Chaque fichier contient un canary token caché (UUID dans les métadonnées)
qui permettrait d'identifier le fichier s'il est exfiltré et publié sur un
forum / leak site.

Usage : sudo python3 generate_fake_files.py
"""
from __future__ import annotations

import os
import random
import string
import sys
import uuid
from datetime import date, datetime, timedelta
from pathlib import Path

try:
    from openpyxl import Workbook
    from openpyxl.styles import Font, PatternFill, Alignment
except ImportError:
    sys.stderr.write("Manque openpyxl : pip install openpyxl\n"); sys.exit(1)

try:
    from docx import Document
    from docx.shared import Pt, RGBColor
except ImportError:
    sys.stderr.write("Manque python-docx : pip install python-docx\n"); sys.exit(1)

try:
    from reportlab.lib.pagesizes import A4
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.lib.units import cm
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
    from reportlab.lib import colors
except ImportError:
    sys.stderr.write("Manque reportlab : pip install reportlab\n"); sys.exit(1)


BASE = Path(os.environ.get("HONEYPOT_BASE", "/srv/samba"))
TENANT = os.environ.get("HONEYPOT_TENANT", "srvdomaine")

# ───────── Données plausibles inventées ─────────

NOMS_ENTREPRISES = [
    "Dupont Industries SARL", "Société Générale Bâtiment", "TechniBureau SAS",
    "Atelier Métallurgique du Nord", "Cabinet Comptable Lefèvre",
    "Imprimerie Moderne Lyon", "Logistique Express France", "BTP Méditerranée",
    "Ets Martin & Fils", "Compagnie Maritime Bordeaux", "Énergie Verte SCOP",
    "Pharmacie Centrale Tours", "Boulangerie La Tradition", "Garage Renault Beauvais",
    "Cave des Vignerons d'Alsace", "Hôtel Restaurant La Fontaine",
    "Coiffure Élégance Paris", "Plomberie Durand", "Peinture Décor Sud",
]

NOMS_FRANCAIS = [
    ("Martin", "Pierre"), ("Bernard", "Marie"), ("Dubois", "Jean"),
    ("Thomas", "Sophie"), ("Robert", "Laurent"), ("Richard", "Catherine"),
    ("Petit", "Nathalie"), ("Durand", "Patrick"), ("Leroy", "Sylvie"),
    ("Moreau", "Christine"), ("Simon", "François"), ("Laurent", "Michel"),
    ("Lefebvre", "Isabelle"), ("Michel", "Philippe"), ("Garcia", "Anne"),
    ("Roux", "Bernard"), ("Fournier", "Monique"), ("Girard", "Alain"),
    ("Bonnet", "Brigitte"), ("Dupont", "Daniel"), ("Lambert", "Véronique"),
    ("Fontaine", "Jacques"), ("Rousseau", "Françoise"), ("Vincent", "Henri"),
]

VILLES = ["Paris", "Lyon", "Marseille", "Toulouse", "Nice", "Nantes", "Strasbourg",
          "Montpellier", "Bordeaux", "Lille", "Rennes", "Reims", "Le Havre", "Toulon"]


def fake_siret() -> str:
    return f"{random.randint(100,999)} {random.randint(100,999)} {random.randint(100,999)} {random.randint(10000,99999)}"


def fake_iban_fr() -> str:
    digits = "".join(random.choices(string.digits, k=23))
    return f"FR{random.randint(10,99)} {digits[0:5]} {digits[5:10]} {digits[10:21]} {digits[21:23]}"


def fake_phone_fr() -> str:
    return f"+33 {random.randint(1,7)} {random.randint(10,99)} {random.randint(10,99)} {random.randint(10,99)} {random.randint(10,99)}"


def fake_email(prenom: str, nom: str, domain: str = "corp.local") -> str:
    return f"{prenom.lower()}.{nom.lower().replace(' ', '')}@{domain}"


def fake_nir() -> str:
    sex = random.choice([1, 2])
    year = random.randint(50, 99)
    month = random.randint(1, 12)
    return f"{sex} {year:02d} {month:02d} {random.randint(1,99):02d} {random.randint(100,999)} {random.randint(100,999)}"


def fake_canary_uuid() -> str:
    return str(uuid.uuid4())


# ───────── Faux fichiers Excel ─────────

def make_facturier(path: Path, year: int, month: int):
    wb = Workbook()
    ws = wb.active
    ws.title = f"Factures {month:02d}-{year}"

    # En-tête
    ws["A1"] = f"Facturation {NOMS_ENTREPRISES[hash(TENANT) % len(NOMS_ENTREPRISES)]}"
    ws["A1"].font = Font(bold=True, size=14)
    ws["A2"] = f"Période : {month:02d}/{year}"
    ws["A3"] = f"SIRET : {fake_siret()}"

    headers = ["N° Facture", "Date", "Client", "Désignation", "HT (€)", "TVA 20% (€)", "TTC (€)", "Statut"]
    for i, h in enumerate(headers, 1):
        c = ws.cell(row=5, column=i, value=h)
        c.font = Font(bold=True, color="FFFFFF")
        c.fill = PatternFill("solid", fgColor="0070C0")
        c.alignment = Alignment(horizontal="center")

    designations = ["Prestations conseil", "Maintenance trimestrielle", "Fourniture matériel",
                    "Formation utilisateurs", "Audit sécurité", "Développement spécifique",
                    "Hébergement infrastructure", "Licences logicielles", "Support technique"]

    statuts = ["Payée", "En attente", "En attente", "Payée", "Relancée", "Payée"]

    row = 6
    total_ht = 0
    for n in range(1, 35):
        ht = round(random.uniform(450, 8500), 2)
        tva = round(ht * 0.20, 2)
        ttc = round(ht + tva, 2)
        total_ht += ht
        d = date(year, month, random.randint(1, 28))
        ws.cell(row=row, column=1, value=f"FAC-{year}-{month:02d}-{n:04d}")
        ws.cell(row=row, column=2, value=d.strftime("%d/%m/%Y"))
        ws.cell(row=row, column=3, value=random.choice(NOMS_ENTREPRISES))
        ws.cell(row=row, column=4, value=random.choice(designations))
        ws.cell(row=row, column=5, value=ht)
        ws.cell(row=row, column=6, value=tva)
        ws.cell(row=row, column=7, value=ttc)
        ws.cell(row=row, column=8, value=random.choice(statuts))
        row += 1

    # Totaux
    ws.cell(row=row+1, column=4, value="TOTAL HT").font = Font(bold=True)
    ws.cell(row=row+1, column=5, value=round(total_ht, 2)).font = Font(bold=True)

    # Largeur colonnes
    for col_letter, w in zip("ABCDEFGH", [18, 12, 35, 28, 12, 14, 14, 14]):
        ws.column_dimensions[col_letter].width = w

    # Canary token caché dans propriétés document
    wb.properties.subject = f"unisoc-canary-{fake_canary_uuid()}"
    wb.properties.keywords = "comptabilite, factures, archive"
    wb.save(path)


def make_salaires(path: Path, year: int, month: int):
    wb = Workbook()
    ws = wb.active
    ws.title = f"Paie {month:02d}-{year}"
    ws["A1"] = f"Bulletin de salaires - {month:02d}/{year}"
    ws["A1"].font = Font(bold=True, size=14)

    headers = ["Matricule", "Nom", "Prénom", "NIR", "Poste", "Brut (€)", "Net (€)", "IBAN"]
    for i, h in enumerate(headers, 1):
        c = ws.cell(row=3, column=i, value=h)
        c.font = Font(bold=True, color="FFFFFF")
        c.fill = PatternFill("solid", fgColor="C00000")

    postes = ["Comptable", "Assistant·e direction", "Commercial·e", "Technicien·ne",
              "Chef de projet", "Développeur·se", "Manager", "Responsable RH",
              "Magasinier·ère", "Standardiste", "Directeur·rice"]

    row = 4
    for i, (nom, prenom) in enumerate(NOMS_FRANCAIS[:18], 1):
        brut = round(random.uniform(2200, 6500), 2)
        net = round(brut * 0.78, 2)
        ws.cell(row=row, column=1, value=f"M{i:04d}")
        ws.cell(row=row, column=2, value=nom)
        ws.cell(row=row, column=3, value=prenom)
        ws.cell(row=row, column=4, value=fake_nir())
        ws.cell(row=row, column=5, value=random.choice(postes))
        ws.cell(row=row, column=6, value=brut)
        ws.cell(row=row, column=7, value=net)
        ws.cell(row=row, column=8, value=fake_iban_fr())
        row += 1

    for col, w in zip("ABCDEFGH", [10, 14, 14, 18, 24, 12, 12, 30]):
        ws.column_dimensions[col].width = w

    wb.properties.subject = f"unisoc-canary-{fake_canary_uuid()}"
    wb.save(path)


def make_balance(path: Path, year: int, month: int):
    wb = Workbook()
    ws = wb.active
    ws.title = "Balance"
    ws["A1"] = f"Balance comptable {month:02d}/{year}"
    ws["A1"].font = Font(bold=True, size=14)

    headers = ["Compte", "Libellé", "Débit (€)", "Crédit (€)", "Solde (€)"]
    for i, h in enumerate(headers, 1):
        ws.cell(row=3, column=i, value=h).font = Font(bold=True)

    comptes = [
        ("101000", "Capital social"),
        ("106000", "Réserves"),
        ("164000", "Emprunts auprès des établissements de crédit"),
        ("411000", "Clients"),
        ("401000", "Fournisseurs"),
        ("445660", "TVA déductible"),
        ("445710", "TVA collectée"),
        ("512000", "Banque"),
        ("530000", "Caisse"),
        ("607000", "Achats marchandises"),
        ("613000", "Locations"),
        ("616000", "Primes assurances"),
        ("641000", "Rémunération du personnel"),
        ("645000", "Charges sociales"),
        ("707000", "Ventes de marchandises"),
        ("706000", "Prestations de services"),
    ]
    row = 4
    for compte, libelle in comptes:
        debit = round(random.uniform(0, 95000), 2) if random.random() > 0.3 else 0
        credit = round(random.uniform(0, 95000), 2) if random.random() > 0.3 else 0
        solde = round(debit - credit, 2)
        ws.cell(row=row, column=1, value=compte)
        ws.cell(row=row, column=2, value=libelle)
        ws.cell(row=row, column=3, value=debit)
        ws.cell(row=row, column=4, value=credit)
        ws.cell(row=row, column=5, value=solde)
        row += 1

    for col, w in zip("ABCDE", [12, 50, 14, 14, 14]):
        ws.column_dimensions[col].width = w

    wb.properties.subject = f"unisoc-canary-{fake_canary_uuid()}"
    wb.save(path)


# ───────── Faux PDF schéma réseau ─────────

def make_schema_reseau(path: Path):
    doc = SimpleDocTemplate(str(path), pagesize=A4, topMargin=2*cm, bottomMargin=2*cm)
    styles = getSampleStyleSheet()
    story = []

    story.append(Paragraph("Schéma réseau interne — DIFFUSION RESTREINTE", styles["Title"]))
    story.append(Spacer(1, 0.5*cm))
    story.append(Paragraph(f"Document : Schema-reseau-{datetime.now().year}.pdf", styles["Normal"]))
    story.append(Paragraph(f"Référence : INFRA-{random.randint(1000,9999)}", styles["Normal"]))
    story.append(Paragraph(f"Classification : Confidentiel — usage interne", styles["Normal"]))
    story.append(Spacer(1, 1*cm))

    story.append(Paragraph("Topologie L2/L3", styles["Heading2"]))
    story.append(Paragraph(
        "Architecture réseau du site siège — segmentation VLAN par fonction. "
        "Cœur de réseau redondé en HSRP. Accès Internet via firewall principal "
        "(FortiGate 100F) en HA actif/passif.", styles["Normal"]))
    story.append(Spacer(1, 0.5*cm))

    # Table équipements
    data = [
        ["Équipement", "Modèle", "IP Mgmt", "VLAN", "Localisation"],
        ["fw-core-01", "FortiGate 100F", "192.168.1.1", "1", "Salle serveur"],
        ["sw-core-01", "Cisco Catalyst 9300", "192.168.1.2", "1", "Salle serveur"],
        ["sw-acc-01", "Cisco Catalyst 2960", "192.168.10.10", "10 (Bureaux)", "Étage 1"],
        ["sw-acc-02", "Cisco Catalyst 2960", "192.168.10.11", "10 (Bureaux)", "Étage 2"],
        ["sw-srv-01", "Cisco Nexus 5000", "192.168.20.10", "20 (Serveurs)", "Salle serveur"],
        ["dc01-prod", "DC AD primaire", "192.168.20.5", "20", "Salle serveur"],
        ["dc02-bkp", "DC AD secondaire", "192.168.20.6", "20", "Salle serveur"],
        ["srv-fileshare", "Synology RS3621", "192.168.20.15", "20", "Salle serveur"],
        ["srv-veeam", "Veeam Backup 11", "192.168.20.20", "20", "Salle serveur"],
        ["srv-erp", "SAP B1 v10", "192.168.20.30", "20", "Salle serveur"],
        ["wifi-cnt", "Cisco WLC", "192.168.30.5", "30 (WiFi)", "Salle serveur"],
    ]
    table = Table(data, colWidths=[3.5*cm, 4*cm, 3*cm, 3*cm, 3.5*cm])
    table.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), colors.HexColor("#0070C0")),
        ('TEXTCOLOR', (0,0), (-1,0), colors.white),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('GRID', (0,0), (-1,-1), 0.5, colors.grey),
        ('FONTSIZE', (0,0), (-1,-1), 8),
    ]))
    story.append(table)
    story.append(PageBreak())

    story.append(Paragraph("Plan d'adressage IP", styles["Heading2"]))
    plan = [
        ["VLAN", "Subnet", "Usage", "Gateway", "DHCP"],
        ["1", "192.168.1.0/24", "Mgmt + transit", "192.168.1.1", "Static"],
        ["10", "192.168.10.0/24", "Bureaux", "192.168.10.1", "192.168.10.50-200"],
        ["20", "192.168.20.0/24", "Serveurs", "192.168.20.1", "Static"],
        ["30", "192.168.30.0/24", "WiFi corporate", "192.168.30.1", "192.168.30.50-200"],
        ["99", "192.168.99.0/24", "DMZ", "192.168.99.1", "Static"],
    ]
    t2 = Table(plan, colWidths=[2*cm, 4*cm, 4*cm, 3.5*cm, 4.5*cm])
    t2.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), colors.HexColor("#0070C0")),
        ('TEXTCOLOR', (0,0), (-1,0), colors.white),
        ('GRID', (0,0), (-1,-1), 0.5, colors.grey),
        ('FONTSIZE', (0,0), (-1,-1), 9),
    ]))
    story.append(t2)
    story.append(Spacer(1, 1*cm))

    story.append(Paragraph(f"<i>Document généré le {datetime.now().strftime('%d/%m/%Y')} — "
                          f"référence interne : {fake_canary_uuid()[:8]}</i>",
                          styles["Italic"]))

    doc.build(story)


# ───────── Faux Word "Mots de passe admin" ─────────

def make_admin_passwords(path: Path):
    doc = Document()
    doc.add_heading("Comptes Administrateur — DIFFUSION RESTREINTE", 0)
    doc.add_paragraph("Document confidentiel — usage IT uniquement.").italic = True
    doc.add_paragraph()

    doc.add_heading("Comptes système", 1)
    table = doc.add_table(rows=1, cols=4)
    table.style = "Light Grid"
    hdr = table.rows[0].cells
    hdr[0].text = "Système"; hdr[1].text = "Login"; hdr[2].text = "Mot de passe"; hdr[3].text = "Notes"

    accounts = [
        ("Active Directory (DC01)", "Administrateur", "P@ssw0rd-AD-2024!", "Domain Admin"),
        ("Veeam Backup", "veeam_admin", "V33m!Backup#2025", "Console v11"),
        ("FortiGate FW", "fw_admin", "F0rt1G@te!Master", "Cisco AnyConnect"),
        ("vCenter ESXi", "root@vcenter", "Vc3nt3r#R00t!", "Cluster prod"),
        ("Synology NAS", "admin", "N@s-RS3621-2024", "Volume backup principal"),
        ("Switch Core Cisco", "enable", "Cisco!Core#2025", "config-t password"),
        ("SAP B1 sa", "sa", "S@P-2024!Pwd", "Compte sa SQL Server"),
        ("Microsoft 365 GA", "ga@corp.local", "M$365!GlobalAdmin#", "Avec MFA"),
        ("WiFi Corporate WPA2", "(SSID Corp-Bureaux)", "WiFiCorp2024Secure!", "Rotated annual"),
        ("Telnet console (legacy)", "admin", "admin1234", "À supprimer urgent"),
    ]
    for sys_name, login, pwd, notes in accounts:
        row = table.add_row().cells
        row[0].text = sys_name
        row[1].text = login
        row[2].text = pwd
        row[3].text = notes

    doc.add_paragraph()
    doc.add_heading("Procédure de rotation", 1)
    doc.add_paragraph(
        "Les mots de passe administrateurs sont à modifier tous les 90 jours "
        "selon la politique sécurité interne. La dernière rotation a eu lieu "
        "le 12/01/2026. Prochaine rotation prévue : 12/04/2026."
    )

    doc.add_paragraph()
    p = doc.add_paragraph(f"Référence document : {fake_canary_uuid()}")
    p.runs[0].font.size = Pt(8); p.runs[0].font.color.rgb = RGBColor(128, 128, 128)

    doc.core_properties.title = "Comptes Administrateur"
    doc.core_properties.subject = f"unisoc-canary-{fake_canary_uuid()}"
    doc.core_properties.keywords = "admin, mots de passe, confidentiel"
    doc.save(path)


def make_inventaire_postes(path: Path):
    wb = Workbook()
    ws = wb.active
    ws.title = "Inventaire postes"
    ws["A1"] = "Inventaire postes informatiques"
    ws["A1"].font = Font(bold=True, size=14)

    headers = ["Hostname", "Utilisateur", "Modèle", "OS", "RAM", "Disque", "IP", "Adresse MAC"]
    for i, h in enumerate(headers, 1):
        c = ws.cell(row=3, column=i, value=h)
        c.font = Font(bold=True, color="FFFFFF")
        c.fill = PatternFill("solid", fgColor="0070C0")

    modeles = ["Dell Latitude 5530", "HP EliteBook 840 G9", "Lenovo ThinkPad T14",
               "Microsoft Surface Pro 9", "Dell OptiPlex 7090", "HP ProDesk 600 G6"]
    oses = ["Windows 11 Pro 23H2", "Windows 10 Pro 22H2", "Ubuntu 22.04 LTS"]

    row = 4
    for i, (nom, prenom) in enumerate(NOMS_FRANCAIS, 1):
        mac = ":".join(f"{random.randint(0,255):02X}" for _ in range(6))
        ws.cell(row=row, column=1, value=f"PC-{prenom[:3].upper()}{nom[:3].upper()}")
        ws.cell(row=row, column=2, value=f"{prenom} {nom}")
        ws.cell(row=row, column=3, value=random.choice(modeles))
        ws.cell(row=row, column=4, value=random.choice(oses))
        ws.cell(row=row, column=5, value=f"{random.choice([8,16,32])} GB")
        ws.cell(row=row, column=6, value=f"{random.choice([256,512,1024])} GB SSD")
        ws.cell(row=row, column=7, value=f"192.168.10.{50+i}")
        ws.cell(row=row, column=8, value=mac)
        row += 1

    for col, w in zip("ABCDEFGH", [16, 22, 28, 28, 8, 14, 16, 20]):
        ws.column_dimensions[col].width = w

    wb.properties.subject = f"unisoc-canary-{fake_canary_uuid()}"
    wb.save(path)


def make_acces_vpn_txt(path: Path):
    content = f"""# Accès VPN distant — Confidentiel
# Last update : {datetime.now().strftime('%d/%m/%Y')}

## Configuration OpenVPN client (utilisateurs nomades)

Serveur :     vpn.corp.local
Port :        1194/UDP
Protocole :   OpenVPN 2.5
Certificat :  ca-corp-2024.crt
Auth :        cert + LDAP

## Comptes VPN actifs

User                    | Service       | Last seen
------------------------|---------------|-------------
{NOMS_FRANCAIS[0][1].lower()}.{NOMS_FRANCAIS[0][0].lower()}      | Direction     | {(datetime.now() - timedelta(days=1)).strftime('%d/%m/%Y')}
{NOMS_FRANCAIS[1][1].lower()}.{NOMS_FRANCAIS[1][0].lower()}      | Compta        | {(datetime.now() - timedelta(days=2)).strftime('%d/%m/%Y')}
{NOMS_FRANCAIS[2][1].lower()}.{NOMS_FRANCAIS[2][0].lower()}     | IT            | {(datetime.now() - timedelta(hours=3)).strftime('%d/%m/%Y')}
{NOMS_FRANCAIS[3][1].lower()}.{NOMS_FRANCAIS[3][0].lower()}     | Commercial    | {(datetime.now() - timedelta(days=7)).strftime('%d/%m/%Y')}

## Procédure de connexion d'urgence

En cas de perte d'accès au réseau corporate :

1. Bypass VPN admin :  ssh root@vpn-bypass.corp.local -p 2222
   Mot de passe : {fake_admin_password()}
2. Console iLO HP :    https://192.168.20.10:443
3. iDRAC Dell :        https://192.168.20.11:443

## Contact urgence IT
- Patrick Durand (resp. IT) : +33 6 {random.randint(10,99)} {random.randint(10,99)} {random.randint(10,99)} {random.randint(10,99)}
- Astreinte 24/7 :            +33 1 {random.randint(40,49)} {random.randint(10,99)} {random.randint(10,99)} {random.randint(10,99)}

# REF: {fake_canary_uuid()}
"""
    path.write_text(content, encoding="utf-8")


def fake_admin_password() -> str:
    return random.choice([
        "AdminBypass2024!", "Emergency-Root#2025", "BkpAdmin$2024",
        "VPN-Bypass!2024", "RootEmergency#2025"
    ])


# ───────── Faux contrats RH ─────────

def make_contrat_cdi(path: Path, nom: str, prenom: str):
    doc = Document()
    doc.add_heading("CONTRAT DE TRAVAIL À DURÉE INDÉTERMINÉE", 0)
    doc.add_paragraph()
    doc.add_paragraph(f"Entre les soussignés :").bold = True

    company = NOMS_ENTREPRISES[hash(TENANT) % len(NOMS_ENTREPRISES)]
    doc.add_paragraph(
        f"La société {company}, SIRET {fake_siret()}, dont le siège est situé "
        f"15 rue {random.choice(['de la République','Victor Hugo','Pasteur','Jean Jaurès'])}, "
        f"{random.choice(VILLES)}, représentée par son dirigeant, "
        f"ci-après désignée « l'Employeur »,"
    )
    doc.add_paragraph("D'une part,")
    doc.add_paragraph()
    doc.add_paragraph(f"Et")
    doc.add_paragraph(
        f"M./Mme {prenom} {nom}, demeurant à {random.choice(VILLES)}, "
        f"NIR {fake_nir()}, ci-après désigné·e « le Salarié »,"
    )
    doc.add_paragraph("D'autre part,")
    doc.add_paragraph()

    doc.add_heading("Article 1 — Engagement", 1)
    doc.add_paragraph(
        f"L'Employeur engage le Salarié en qualité de "
        f"{random.choice(['Comptable','Assistant·e direction','Commercial·e','Technicien·ne'])} "
        f"à compter du {(datetime.now() - timedelta(days=random.randint(180, 1500))).strftime('%d/%m/%Y')}."
    )

    doc.add_heading("Article 2 — Rémunération", 1)
    salaire = random.randint(2500, 5500)
    doc.add_paragraph(
        f"En contrepartie de son travail, le Salarié percevra une rémunération "
        f"mensuelle brute de {salaire} € sur 12 mois, à laquelle s'ajouteront "
        f"les éventuelles primes prévues par la convention collective applicable."
    )

    doc.add_heading("Article 3 — Durée du travail", 1)
    doc.add_paragraph(
        "Le Salarié est embauché à temps plein, soit 35 heures hebdomadaires, "
        "réparties du lundi au vendredi de 9h à 17h."
    )

    doc.add_heading("Article 4 — Période d'essai", 1)
    doc.add_paragraph(
        "La période d'essai est fixée à 2 mois, renouvelable une fois sur "
        "l'accord écrit des deux parties."
    )

    doc.add_paragraph()
    doc.add_paragraph(
        f"Fait à {random.choice(VILLES)} le "
        f"{(datetime.now() - timedelta(days=random.randint(180, 1500))).strftime('%d/%m/%Y')}, "
        f"en deux exemplaires originaux."
    )

    doc.add_paragraph()
    doc.add_paragraph("Pour l'Employeur                        Le Salarié")
    doc.add_paragraph()
    doc.add_paragraph(f"REF: {fake_canary_uuid()}").runs[0].font.size = Pt(7)

    doc.core_properties.subject = f"unisoc-canary-{fake_canary_uuid()}"
    doc.save(path)


# ───────── Génération arborescence complète ─────────

def main():
    print(f"[+] Génération arborescence sous : {BASE}")
    BASE.mkdir(parents=True, exist_ok=True)

    # /srv/samba/comptabilite/Archives/<year>/<month>/
    print("[+] Comptabilité — archives 2020-2026")
    for year in [2020, 2021, 2022, 2023, 2024, 2025, 2026]:
        for month in range(1, 13):
            if year == 2026 and month > datetime.now().month:
                break
            d = BASE / "comptabilite" / "Archives" / str(year) / f"{month:02d}-{['Janvier','Fevrier','Mars','Avril','Mai','Juin','Juillet','Aout','Septembre','Octobre','Novembre','Decembre'][month-1]}"
            d.mkdir(parents=True, exist_ok=True)
            try:
                make_facturier(d / "Factures-clients.xlsx", year, month)
                make_balance(d / "Balance-comptable.xlsx", year, month)
                if month % 3 == 0:
                    make_salaires(d / "Salaires.xlsx", year, month)
            except Exception as e:
                print(f"    [!] {d}: {e}")

    # /srv/samba/informatique/
    print("[+] Informatique — schémas, comptes, inventaire")
    info = BASE / "informatique"
    (info / "Reseau").mkdir(parents=True, exist_ok=True)
    (info / "Comptes-Admin").mkdir(parents=True, exist_ok=True)
    (info / "Postes").mkdir(parents=True, exist_ok=True)
    (info / "Sauvegardes").mkdir(parents=True, exist_ok=True)

    make_schema_reseau(info / "Reseau" / "Schema-reseau-2026.pdf")
    make_schema_reseau(info / "Reseau" / "Plan-adressage-IP.pdf")
    make_admin_passwords(info / "Comptes-Admin" / "Mots-de-passe-admin.docx")
    make_admin_passwords(info / "Comptes-Admin" / "Comptes-services.docx")
    make_inventaire_postes(info / "Postes" / "Inventaire-2026.xlsx")
    make_acces_vpn_txt(info / "Comptes-Admin" / "Acces-VPN.txt")

    # /srv/samba/RH/
    print("[+] RH — contrats, paie")
    rh = BASE / "RH" / "Contrats"
    rh.mkdir(parents=True, exist_ok=True)
    for nom, prenom in NOMS_FRANCAIS[:8]:
        make_contrat_cdi(rh / f"CDI-{nom}-{prenom}.docx", nom, prenom)

    # /srv/samba/Direction/
    print("[+] Direction — bilans annuels")
    direction = BASE / "Direction"
    direction.mkdir(parents=True, exist_ok=True)
    for year in [2024, 2025]:
        make_balance(direction / f"Bilan-{year}.xlsx", year, 12)

    # Permissions
    print("[+] Permissions r/w...")
    os.system(f"chmod -R 755 {BASE}")

    print()
    print(f"[+] Arborescence générée :")
    os.system(f"find {BASE} -type f | head -30")
    n_files = sum(1 for _ in BASE.rglob("*") if _.is_file())
    print(f"\n[+] Total : {n_files} fichiers leurres générés.")


if __name__ == "__main__":
    main()
