---
# Playbook 03: Docker Setup
# Install Docker CE and Docker Compose v2

- name: Docker Installation
  hosts: all
  become: yes
  
  tasks:
    - name: Remove old Docker installations
      apt:
        name:
          - docker
          - docker-engine
          - docker.io
          - containerd
          - runc
          - docker-compose
        state: absent
        purge: yes

    - name: Remove old Docker data directories
      file:
        path: "{{ item }}"
        state: absent
      loop:
        - /var/lib/docker
        - /var/lib/containerd
        - /etc/docker

    - name: Add Docker GPG key
      apt_key:
        url: https://download.docker.com/linux/ubuntu/gpg
        state: present

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

    - name: Install Docker CE
      apt:
        name:
          - docker-ce
          - docker-ce-cli
          - containerd.io
          - docker-buildx-plugin
          - docker-compose-plugin
        state: present
        update_cache: yes

    - name: Create Docker daemon configuration
      copy:
        dest: /etc/docker/daemon.json
        content: |
          {
            "log-driver": "json-file",
            "log-opts": {
              "max-size": "10m",
              "max-file": "3"
            },
            "storage-driver": "overlay2",
            "userland-proxy": false,
            "live-restore": true
          }
      notify: restart docker

    - name: Create docker group
      group:
        name: docker
        state: present

    - name: Add user to docker group
      user:
        name: "{{ ansible_user }}"
        groups: docker
        append: yes

    - name: Create deployment directory
      file:
        path: "{{ deployment_dir }}"
        state: directory
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: '0755'

    - name: Start and enable Docker
      service:
        name: docker
        state: started
        enabled: yes

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

    - name: Display Docker version
      debug:
        msg: "Docker installed: {{ docker_version.stdout }}"

    - name: Verify Docker Compose installation
      command: docker compose version
      register: compose_version
      changed_when: false

    - name: Display Docker Compose version
      debug:
        msg: "Docker Compose installed: {{ compose_version.stdout }}"

  handlers:
    - name: restart docker
      service:
        name: docker
        state: restarted
