---

- name: Install prerequisites
  hosts: localhost
  connection: local
  become: yes
  vars_files:
    - config.build.yaml
    - config.defaults.yaml
    - ../config.yaml

  tasks:

  - name: Checking Linux distro
    debug:
      msg:
        - "Distro name: {{ ansible_distribution }} Distro version: {{ ansible_distribution_major_version }}"

  - name: Prepare Python 3
    import_tasks: tasks_python.yaml

  - name: Install required system packages
    package:
      name:
        - git
        - ca-certificates
        - curl
      update_cache: yes
      state: latest

  - name: Install required python packages
    pip:
      name:
        # for "docker_image" module
        - docker==4.3.1
        # for "docker_compose" module
        - docker-compose==1.27.4
        # for dig lookup
        - dnspython==1.16.0
        # fix for python 3.5
        - jsonschema==3.0.2

  - name: Install Docker on Ubuntu/Debian
    import_tasks: tasks_docker_ubuntu.yaml
    when: ansible_distribution == 'Ubuntu' or ansible_distribution == 'Debian' 

  - name: Install Docker on CentOS
    import_tasks: tasks_docker_centos.yaml
    when: ansible_distribution == 'CentOS'

  - name: Warning about manual Docker installation
    debug:
      msg: "I do not know now to install Docker on your OS! Please install docker manually."
    when: ansible_distribution != 'Ubuntu' and ansible_distribution != 'Debian' and ansible_distribution != 'CentOS'

  - name: Ensure Docker is started and enabled at boot
    service:
      name: docker
      state: started
      enabled: true

  - name: Ensure current user is added to the docker group
    user:
      name: "{{ lookup('env', 'USER') }}"
      groups: docker
      append: true
    when: "ansible_user_id != 'root'"

  - name: Download docker-compose
    get_url:
      url: https://github.com/docker/compose/releases/download/1.26.0/docker-compose-{{ ansible_system }}-{{ ansible_machine }}
      dest: /usr/local/bin/docker-compose
      mode: 0755
      force: yes

  - name: Download docker-compose autocompletion (for bash only)
    get_url:
      url: https://raw.githubusercontent.com/docker/compose/1.26.0/contrib/completion/bash/docker-compose
      dest: /etc/bash_completion.d/docker-compose
    when: "'/bash' in ansible_user_shell"

#  - name: Ensure Headwind Remote is not running
#    docker_compose:
#      project_src: ../
#      state: absent
#      stopped: yes
#      remove_volumes: yes
#      timeout: 30

#  - name: Start Headwind Remote
#    docker_compose:
#      project_src: ../
#      state: present
#      stopped: no
