---
# Linux-specific Docker installation (apt-based)

- name: Install required system packages for Docker
  ansible.builtin.apt:
    name:
      - ca-certificates
      - curl
      - gnupg
      - lsb-release
    state: present
    update_cache: true

- name: Create directory for Docker GPG key
  ansible.builtin.file:
    path: /etc/apt/keyrings
    state: directory
    mode: '0755'

- name: Add Docker GPG key
  ansible.builtin.shell:
    cmd: |
      set -o pipefail
      curl -fsSL https://download.docker.com/linux/{{ ansible_distribution | lower }}/gpg | \
        gpg --dearmor -o /etc/apt/keyrings/docker.gpg
      chmod a+r /etc/apt/keyrings/docker.gpg
    creates: /etc/apt/keyrings/docker.gpg
    executable: /bin/bash

- name: Add Docker repository
  ansible.builtin.shell:
    cmd: |
      set -o pipefail
      echo "deb [arch=$(dpkg --print-architecture) \
        signed-by=/etc/apt/keyrings/docker.gpg] \
        https://download.docker.com/linux/{{ ansible_distribution | lower }} \
        $(lsb_release -cs) stable" | \
        tee /etc/apt/sources.list.d/docker.list > /dev/null
    creates: /etc/apt/sources.list.d/docker.list
    executable: /bin/bash

- name: Update apt cache after adding Docker repo
  ansible.builtin.apt:
    update_cache: true

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

- name: Ensure Docker service is started and enabled
  ansible.builtin.systemd:
    name: docker
    state: started
    enabled: true

- name: Add user to docker group
  ansible.builtin.user:
    name: "{{ openclaw_user }}"
    groups: docker
    append: true

- name: Reset SSH connection to apply docker group
  ansible.builtin.meta: reset_connection
