---
- hosts: debian_vm
  gather_facts: yes

  vars_prompt:
    - name: "hostname_var"
      prompt: "Entrez le nom d'hôte pour la machine"
      private: no

    - name: "user_name"
      prompt: "Entrez le nom de l'utilisateur à créer"
      private: no

    - name: "user_password"
      prompt: "Entrez le mot de passe pour l'utilisateur"
      private: yes  # Le mot de passe ne sera pas affiché lors de la saisie

    - name: "root_password"
      prompt: "Entrez le mot de passe pour root"
      private: yes  # Le mot de passe ne sera pas affiché lors de la saisie

  tasks:
    # 1. Installer sudo si nécessaire
    - name: Passer à root et installer sudo
      become: yes
      become_user: root
      become_method: su
      command: apt install sudo -y
      vars:
        ansible_become_pass: "{{ root_password }}"
      register: result
      async: 60
      poll: 0

    - name: Afficher le résultat de l'installation de sudo
      debug:
        var: result

    # 2. Ajouter l'utilisateur au groupe sudo
    - name: Ajouter l'utilisateur au groupe sudo
      user:
        name: "{{ user_name }}"
        groups: sudo
        append: yes
      become: yes
      become_user: root
      become_method: su
      vars:
        ansible_become_pass: "{{ root_password }}"

    # 3. Mettre à jour les paquets
    - name: Mettre à jour les paquets
      apt:
        update_cache: yes
      become: yes
      become_user: root
      become_method: su
      vars:
        ansible_become_pass: "{{ root_password }}"

    # 4. Configurer le hostname
    - name: Configurer le hostname
      hostname:
        name: "{{ hostname_var }}"
      become: yes
      become_user: root
      become_method: su
      vars:
        ansible_become_pass: "{{ root_password }}"

    # 5. Changer le mot de passe root
    - name: Changer le mot de passe root
      user:
        name: root
        password: "{{ root_password | password_hash('sha512') }}"
      become: yes
      become_user: root
      become_method: su
      vars:
        ansible_become_pass: "{{ root_password }}"

    # 6. Configurer l'utilisateur spécifié
    - name: Configurer l'utilisateur
      user:
        name: "{{ user_name }}"
        password: "{{ user_password | password_hash('sha512') }}"
        shell: /bin/bash
        groups: sudo
        state: present
      become: yes
      become_user: root
      become_method: su
      vars:
        ansible_become_pass: "{{ root_password }}"
