---
# file: roles/docker/tasks/docker-rootless.yml

- name: "install dependencies"
  apt:
    name:
      - uidmap
      - docker-ce-rootless-extras
      - slirp4netns

- name: "get uidnumber of user {{ docker_user }}"
  ansible.builtin.command:
    cmd: "id -u {{ docker_user }}"
  changed_when: false
  check_mode: false
  register: rootless_uid

- name: "check if /run/docker.sock exists"
  stat:
    path: "/run/user/{{ rootless_uid.stdout }}/docker.sock"
  register: rootless_conf

- name: "stop any running root instances of docker daemon"
  systemd:
    name: "{{ item }}"
    state: stopped
    enabled: false
  loop:
    - docker.service
    - docker.socket

- name: "remove docker.sock file"
  file:
    path: /var/run/docker.sock
    state: absent

- name: "set 65536 subordinate UIDs/GUIDs for the user"
  lineinfile:
    path: "/etc/{{ item }}"
    insertafter: EOF
    line: "{{ docker_user }}:100000:65536"
  loop:
    - subuid
    - subgid

- name: "install rootless docker (ssh root@server 'machinectl -q shell {{ docker_user }}@ dockerd-rootless-setuptool.sh install)"
  remote_user: root
  become: true
  become_method: community.general.machinectl
  become_user: "{{ docker_user }}"
  vars:
    ansible_ssh_pipelining: false # https://github.com/ansible/ansible/issues/81254
  ansible.builtin.command: /usr/bin/dockerd-rootless-setuptool.sh install
  when: not rootless_conf.stat.exists

- name: "enable and start rootless docker"
  remote_user: root
  become: true
  become_method: community.general.machinectl
  become_user: "{{ docker_user }}"
  vars:
    ansible_ssh_pipelining: false # https://github.com/ansible/ansible/issues/81254
  systemd:
    name: docker.service
    state: started
    enabled: true
    scope: user
  ignore_errors: "{{ ansible_check_mode }}"

- name: "decouple rootless docker from user session"
  remote_user: root
  become: true
  become_method: community.general.machinectl
  become_user: "{{ docker_user }}"
  vars:
    ansible_ssh_pipelining: false # https://github.com/ansible/ansible/issues/81254
  ansible.builtin.command: "loginctl enable-linger {{ docker_user }}"
  when: not rootless_conf.stat.exists

- name: "DOCKER_HOST=unix:///run/user/{{ rootless_uid.stdout }}/docker.sock in /etc/environment"
  lineinfile:
    path: /etc/environment
    insertafter: EOF
    line: "DOCKER_HOST=unix:///run/user/{{ rootless_uid.stdout }}/docker.sock"
