---

- hosts: all
  roles:
    - tobiko-ensure-ssh-keys

  tasks:
    - name: copy /etc/resolv.conf
      become: yes
      copy:
        src: /etc/resolv.conf
        dest: /etc/resolv.conf
        owner: root
        group: root
        mode: '0644'

    - name: make /etc/hosts
      become: yes
      template:
        src: hosts.j2
        dest: /etc/hosts
        owner: root
        mode: '0644'

    - name: make ~/.ssh/config file with all nodes
      template:
        src: ssh_config.j2
        dest: /home/vagrant/.ssh/config
        owner: vagrant
        mode: '0600'

    - name: check ICMP connectivity
      shell: |
        set -xe
        ping -c 1 '{{ item.1.ip }}'
        ping -c 1 '{{ item.1.hostname }}'
      changed_when: false
      register: check_icmp_connectivity
      loop: '{{ vagrant_nodes | dictsort }}'

    - name: check SSH connectivity via hostname
      shell: |
        set -xe
        ssh '{{ item.1.ip }}' hostname
        ssh '{{ item.1.hostname }}' hostname
        ssh '{{ item.0 }}' hostname
      changed_when: false
      register: check_ssh_connectivity
      loop: '{{ vagrant_nodes | dictsort }}'


- hosts: primary
  tasks:
    - name: set test_inventory_hostvars_yaml fact
      set_fact:
        test_inventory_hostvars_yaml: |
          ---
          {% for name, node in (vagrant_nodes | dictsort) %}
          {{ name }}:
            ansible_host: {{ node.hostname }}
          {% endfor %}

    - name: set test_inventory_hostvars fact
      set_fact:
        test_inventory_hostvars:
          '{{ test_inventory_hostvars_yaml | from_yaml }}'
        test_inventory_groups: '{{ vagrant_groups }}'

    - debug: var=test_inventory_hostvars
    - debug: var=test_inventory_groups
    - include_role: name=tobiko-inventory


- hosts: all
  tasks:
    - name: disable tempfs on Fedora
      become: yes
      command: systemctl mask tmp.mount  # noqa 303
      when: ansible_distribution == 'Fedora'
      ignore_errors: yes

    - name: Register as user '{{ rh_username }}' and auto-subscribe to available content
      become: yes
      redhat_subscription:
        state: present
        username: '{{ rh_username }}'
        password: '{{ rh_password }}'
        auto_attach: yes
      when:
      - rh_username is defined
      - (rh_username | length) > 0

    - name: update APT database
      apt:
        update_cache: yes
        cache_valid_time: 3600
      become: yes
      when:
        - ansible_os_family == 'Debian'


- hosts: primary
  roles:
    - tobiko-common
  tasks:
    - name: ensure deploy tools are installed
      become: true
      package: name='{{ item }}'
      loop:
        - git
        - rsync

    - name: copy '{{ tobiko_src_dir }}' to '{{ tobiko_dir }}'
      synchronize:
        src: "{{ tobiko_src_dir | realpath }}/."
        dest: "{{ tobiko_dir }}"
        use_ssh_args: yes
        recursive: yes
        rsync_opts:
          - '--exclude-from={{ tobiko_src_dir }}/.gitignore'
