---

- block:

  # only add apt-key, the repository is added in apt_sources ansible role.
  - name: add new docker apt key
    apt_key:
      url: "https://download.docker.com/linux/ubuntu/gpg"

  # we need out local mirror for trusty as the public one is no longer hosted.
  - name: add docker apt repo
    apt_repository:
      repo: "deb [arch=amd64] http://apt-mirror.zooxlabs.com/mirror/download.docker.com/linux/ubuntu trusty stable"
    when:  ansible_distribution_version is version('15.00', '<')

  - name: add docker apt repo
    apt_repository:
      repo: "deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable"
    when: ansible_distribution_version is version('15.00', '>=')

  - name: Install docker engine from apt
    apt:
      name: "docker-ce"
      install_recommends: no
      state: present
      update_cache: yes
    # We've been seeing occasional transient failures with apt.  Until we have
    # a proper solution, just try it again.
    # TOOL-2677
    register: result
    until: result is success
    retries: 2

  - name: Create docker group
    group:
      name: docker

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

  - name: Check if current file exists
    stat:
        path: /etc/default/docker
    register: current_file

  - name: Ensure current file
    file:
      state: touch
      path: /etc/default/docker
    when: not current_file.stat.exists

  - name: Checksum of current
    stat:
      path: /etc/default/docker
    register: current_config

  - name: Copy default config to tmp
    copy:
      src: files/default
      dest: /tmp/docker_default

  - name: Checksum of default config
    stat:
      path: /tmp/docker_default
    register: default_config

  - name: See if file is Zoox managed
    lineinfile:
      dest: /etc/default/docker
      state: present
      line: "# MANAGED BY ZOOX INC"
    register: managed
    check_mode: yes
    ignore_errors: yes

  - debug:
      msg: "The file at /etc/default/docker has been modified from default.
            If this is intentional, ignore this message.  If not, and you would
            like this file to be updated and managed by Zoox, please add the line
            '# MANAGED BY ZOOX INC' (no quotes) to the top of the file and re-run
            the docker role."
    when:   (current_config.stat.checksum != default_config.stat.checksum) and
            (managed.changed)

  - name: Write out DNS Rules
    template:
      src: templates/docker
      dest: /etc/default
      mode: 0644
    when:   (current_config.stat.checksum == default_config.stat.checksum) or
            (not managed.changed) or
            (current_config.stat.size == 0)
    notify:
    - Restart Docker

  become: yes
