# https://docs.docker.com/engine/install/debian/

- name: ensure old docker packages are uninstalled
  apt:
    name:
      - docker
      - docker-engine
      - docker.io
      - containerd
      - runc
    force_apt_get: yes
    purge: yes
    state: absent


- name: add docker repository
  include_tasks: add_docker_repo.yml


- name: install docker and dependencies
  apt:
    name:
      - docker-ce
      - docker-ce-cli
      - containerd.io
      - docker-compose-plugin
      - python3-pip
    force_apt_get: yes
    state: latest


- name: install python docker modules
  pip:
    name:
      - docker
      - docker-compose>=1.7.0
    state: latest


- name: enable and start docker
  service:
    name: "{{ item }}"
    enabled: yes
    state: started
  loop:
    - docker
    - containerd


- name: flush handlers
  meta: flush_handlers


- name: create helloworld container
  docker_container:
    name: hello-world
    image: hello-world
    command_handling: correct
    init: yes
    output_logs: yes
    log_driver: local
    detach: no
    network_mode: none
  register: result
  changed_when: no
  failed_when: "{{ result.container.State.ExitCode != 0 or not ('Hello from Docker!' in result.container.Output) }}"


- name: create docker network
  docker_network:
    name: network
    driver: bridge
    internal: no
    ipam_config:
      - subnet: "{{ docker_network_subnet }}"
        gateway: "{{ docker_network_gateway }}"
        iprange: "{{ docker_network_iprange }}"


- name: save ipv4 forwarding to sysctl startup scripts
  copy:
    dest: /etc/sysctl.d/91-forwarding.conf
    content: "net.ipv4.conf.all.forwarding = 1\n"
    mode: 0644


- name: set ipv4 forwarding
  sysctl:
    name: net.ipv4.conf.all.forwarding
    value: 1
    sysctl_set: yes


- name: change default iptables policy
  iptables:
    chain: FORWARD
    jump: ACCEPT


- name: install iptables-persistent
  apt:
    name: iptables-persistent
    force_apt_get: yes
    state: latest


- name: save current iptables rules
  community.general.iptables_state:
    ip_version: ipv4
    table: filter
    state: saved
    path: /etc/iptables/rules.v4


- name: change docker systemd service
  lineinfile:
    path: /lib/systemd/system/docker.service
    regexp: '^ExecStart='
    line: 'ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock -H tcp://0.0.0.0:{{ docker_remote_port }}'
  notify: update docker unit file
