---
- name: validate role spec
  validate_role_spec:
    spec: load_spec.yaml

# this block will clone the scm provided by config_manager_scm_url and either
# discover the host configuration file or explicitly load a configuration file
# defined by config_manager_scm_file.
- name: retrieve configuration file from scm
  block:
    - name: create temp working directory
      tempfile:
        state: directory
      register: config_manager_working_dir
      changed_when: false

    - name: checkout scm project
      git:
        repo: "{{ config_manager_scm_url }}"
        dest: "{{ config_manager_working_dir.path }}"
      changed_when: false

    - name: discover the configuration file path and load it
      set_fact:
        config_manager_file: "{{ lookup('first_found', search_path) }}"
      vars:
        search_path:
          - "{{ config_manager_working_dir.path }}/{{ ansible_network_os }}/{{ inventory_hostname_short }}"
          - "{{ config_manager_working_dir.path }}/{{ ansible_network_os }}/{{ inventory_hostname_short }}.cfg"
          - "{{ config_manager_working_dir.path }}/{{ inventory_hostname_short }}"
          - "{{ config_manager_working_dir.path }}/{{ inventory_hostname_short }}.cfg"
      when: config_manager_scm_file is undefined

    - name: set the config_manager_file value based on config_manager_scm_file
      set_fact:
        config_manager_file: "{{ config_manager_scm_file }}"
      when: config_manager_scm_file is defined

    - name: remove temporary working dir
      file:
        path: config_manager_working_dir.path
        state: absent
      changed_when: false
  rescue:
    - name: remove temporary working dir
      file:
        path: "{{ config_manager_working_dir.path }}"
        state: absent
      changed_when: false

    - name: fail the host
      fail:
        msg: "no configuration file found for host"
  when: config_manager_scm_url is defined

# if the configuration is provide via a file by setting config_manager_file
# either explicitly or disovered via scm, load the configuration contents and
# hand off config_manager_text to the provider role for implementation.
- name: load config file contents
  set_fact:
    config_manager_text: "{{ lookup('config_template', config_manager_file) | join('\n') }}"
  when: config_manager_file is defined

# validate at this point that config_manager_text is set othewise fail
# the host.
- name: validate config_manager_text is defined
  fail:
    msg: "missing required arg: config_manager_text"
  when: config_manager_text is undefined

- name: invoke network provider
  include_role:
    name: "{{ ansible_network_provider }}"
    tasks_from: config_manager/load
