---
- name: Set up Docker, clone repo, and install packages
  hosts: blogmachine
  tasks:
    - name: Install required dependencies
      become: yes
      apt:
        name:
          - apt-transport-https
          - ca-certificates
          - curl
          - gnupg
          - lsb-release
        state: present
        update_cache: yes
      when: ansible_os_family == "Debian"

    - name: Add Docker's official GPG key
      become: yes
      apt_key:
        url: https://download.docker.com/linux/ubuntu/gpg
        state: present
      when: ansible_os_family == "Debian"

    - name: Add Docker repository
      become: yes
      apt_repository:
        repo: "deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release | lower }} stable"
        state: present
      when: ansible_os_family == "Debian"

    - name: Install Docker
      become: yes
      apt:
        name: docker-ce
        state: present
      when: ansible_os_family == "Debian"

    - name: Ensure Docker service is running
      become: yes
      service:
        name: docker
        state: started
        enabled: yes
      when: ansible_os_family == "Debian"

    - name: Install some packages (e.g., git, curl, vim)
      become: yes
      apt:
        name:
          - git
          - curl
          - vim
        state: present
        update_cache: yes
      when: ansible_os_family == "Debian"

    - name: Clone the Git repository
      git:
        repo: 'ssh://git@gitea.cball5.club:222/cball5/blog.git'  
        dest: '/home/cball5/blog'  
        version: master  
        force: yes  
        ssh_opts: '-o StrictHostKeyChecking=no'


    - name: Verify Docker installation
      become: yes
      command: docker --version
      register: docker_version
      changed_when: false

    - name: Print Docker version
      debug:
        msg: "Docker version is {{ docker_version.stdout }}"
    - name: Check if user is already in the Docker group
      become: yes
      command: id -nG "cball5"
      register: user_groups
      changed_when: false  
    - name: Add user to Docker group if not already present
      become: yes
      user:
        name: "cball5"
        group: docker
        append: yes
      when: "'docker' not in user_groups.stdout"  

    - name: Reboot the system if the user was added to the Docker group
      become: yes
      reboot:
        reboot_timeout: 600
        test_command: whoami  
      when: "'docker' not in user_groups.stdout"  
