---
# tasks file for zoreide

- ansible.builtin.debug:
    msg: "ENABLED = {{ zoreide_enabled }}; zoreide-role; install and configure zoreide HA"

- name: Get $PATH
  ansible.builtin.shell:
    cmd: "echo $PATH"
  register: path_env

- name: check go version is at least 1.21
  when:
    - "zoreide_enabled is true"
    - 'go_path is defined'
    - "'global.update_only' not in ansible_run_tags"
  environment:
      PATH: '{{ go_path }}:{{ path_env }}'
  shell: go version | grep go.1.21
  register: go_check
  ignore_errors: true

- when:
    - 'zoreide_enabled is true'
    - 'go_path is defined'
    - "'global.update_only' not in ansible_run_tags"
    - 'go_check|failed'
  block:
    - name: Install git if needed
      ansible.builtin.package:
        name: git

    - name: Official repo print url
      debug:
        msg: "{{ zoreide_git_url }}"

    - name: Compile zoreide
      become: true
      become_user: root
      block:
        - name: Check if repo is cloned
          stat:
            path: "{{ zoreide_installation_path }}"
          register: installation_path

        - name: Clone repo
          when: 'not installation_path.stat.exists'
          ansible.builtin.git:
            repo: "{{ zoreide_git_url }}"
            dest: "{{ zoreide_installation_path }}"
            single_branch: yes
            version: "{{ zoreide_git_branch }}"

        - name: Update repo
          ansible.builtin.git:
            repo: "{{ zoreide_git_url }}"
            dest: "{{ zoreide_installation_path }}"
            update: yes

        - name: Get $PATH
          ansible.builtin.shell:
            cmd: "echo $PATH"
          register: path_env

        - name: Build executable
          ansible.builtin.shell:
            cmd: "go build"
            chdir: "{{ zoreide_installation_path }}"
          environment:
              PATH: '{{ go_path }}:{{ path_env }}'
          args:
              executable: /bin/bash

        - include_tasks: "install_{{ ansible_service_mgr }}_service.yml"
          ignore_errors: true

        - name: copy zoreide.json config
          copy:
            src: ../files/zoreide.json
            dest: "{{ zoreide_installation_path }}/zoreide.json"
            owner: root
            group: root
            mode: 0660

- name: Configure iptables
  when:
    - "zoreide_enabled is true"
    - "ansible_facts.services['iptables.service'] is defined"
  block:
    - name: Allow related and established connections
      ansible.builtin.iptables:
        chain: INPUT
        protocol: udp
        destination_port: "{{ zoreide_ha_port }}"
        ctstate: NEW
        syn: match
        jump: ACCEPT
        comment: Zoreide HA Port

- name: Save rules with iptables-persistent v6
  ansible.builtin.shell: iptables-save > /etc/iptables/rules.v4