---
# This role assumes the existence of the node manager, which is setup using another role.
- name: get the private IP for the instance
  set_fact:
    node_rpc_ip: "{{ instance_facts.instances[0].network_interfaces[0].private_ip_address }}"
  when: provider == "aws" and public_rpc

- name: use the public IP as the RPC address on DO
  set_fact:
    node_rpc_ip: "{{ ansible_host }}"
  when: provider == "digital-ocean" and public_rpc

- name: check if genesis node is already set up
  become: True
  ansible.builtin.command: safenode-manager status --json
  register: genesis_status

- name: parse genesis node status
  set_fact:
    genesis_exists: "{{ (genesis_status.stdout | from_json).nodes | selectattr('genesis', 'equalto', true) | list | length > 0 }}"
  when: genesis_status.stdout != ""

- name: add genesis node service
  become: True
  ansible.builtin.command:
    argv: "{{ command_args | reject('equalto', omit) | list }}"
  vars:
    command_args:
      - "{{ binary_dir }}/safenode-manager"
      - -v
      - add
      - --first
      - "--rpc-address={{ node_rpc_ip }}"
      - "--rewards-address={{ rewards_address }}"
      - "--max-archived-log-files={{ max_archived_log_files }}"
      - "--max-log-files={{ max_log_files }}"
      - "{{ ('--log-format=' + log_format) if log_format is defined else omit }}"
      - "{{ ('--env=' + env_variables) if env_variables is defined else omit }}"
      - "{{ ('--version=' + version) if version is defined else ('--url=' + node_archive_url) }}"
      - "{{ evm_network_type }}"
      - "{{ ('--rpc-url=' + evm_rpc_url) if evm_network_type == 'evm-custom' else omit }}"
      - "{{ ('--payment-token-address=' + evm_payment_token_address) if evm_network_type == 'evm-custom' else omit }}"
      - "{{ ('--data-payments-address=' + evm_data_payments_address) if evm_network_type == 'evm-custom' else omit }}"
  when: not genesis_exists | default(false)

- name: start the genesis node service
  become: True
  command: safenode-manager -v start --interval 200