---
#--------------------------------------------------------------#
# Preflight                                     [deepflow_check]
#--------------------------------------------------------------#
- name: check deepflow prerequisites
  tags: deepflow_check
  block:
    - name: assert docker is enabled
      assert:
        that:
          - docker_enabled is defined
          - docker_enabled | bool
        fail_msg: "docker_enabled=true is required for deepflow_server role"

    - name: check docker binary exists
      command: docker --version
      changed_when: false

#--------------------------------------------------------------#
# Configure                                      [deepflow_conf]
#--------------------------------------------------------------#
- name: configure deepflow-server stack
  tags: deepflow_conf
  block:
    - name: create deepflow directories
      file:
        path: "{{ item }}"
        state: directory
        owner: root
        group: root
        mode: '0755'
      loop:
        - "{{ deepflow_stack_dir }}"
        - "{{ deepflow_data }}"
        - "{{ deepflow_data }}/server"
        - "{{ deepflow_server_config_dir }}"

    - name: render deepflow environment
      template:
        src: deepflow.env.j2
        dest: "{{ deepflow_env_file }}"
        owner: root
        group: root
        mode: '0640'

    - name: render deepflow server config
      template:
        src: server.yaml.j2
        dest: "{{ deepflow_server_config_file }}"
        owner: root
        group: root
        mode: '0644'

    - name: render deepflow docker compose
      template:
        src: docker-compose.yml.j2
        dest: "{{ deepflow_compose_file }}"
        owner: root
        group: root
        mode: '0644'

    - name: install deepflow systemd unit
      template:
        src: deepflow-server.svc
        dest: "{{ systemd_dir }}/deepflow-server.service"
        owner: root
        group: root
        mode: '0644'

#--------------------------------------------------------------#
# Launch                                            [deepflow_up]
#--------------------------------------------------------------#
- name: launch deepflow-server stack
  tags: deepflow_up
  block:
    - name: start deepflow-server service
      systemd:
        name: deepflow-server
        state: restarted
        enabled: yes
        daemon_reload: yes

    - name: wait for deepflow gRPC port
      wait_for:
        host: 127.0.0.1
        port: "{{ deepflow_server_grpc_port }}"
        timeout: 60

    - name: wait for deepflow app port
      wait_for:
        host: 127.0.0.1
        port: "{{ deepflow_app_port }}"
        timeout: 60
