---
- pause:
    prompt: |
      Enter the local path to your configuration INI file
      (https://trailofbits.github.io/algo/cloud-vultr.html):
  register: _vultr_config
  when:
    - vultr_config is undefined
    - lookup('env', 'VULTR_API_CONFIG')|length <= 0
  no_log: true

- name: Set the token as a fact
  set_fact:
    algo_vultr_config: "{{ vultr_config | default(_vultr_config.user_input) | default(lookup('env', 'VULTR_API_CONFIG'), true) }}"
  no_log: true

- name: Set the Vultr API Key as a fact
  set_fact:
    vultr_api_key: "{{ lookup('ansible.builtin.ini', 'key', section='default', file=algo_vultr_config) }}"

- name: Get regions
  uri:
    url: https://api.vultr.com/v2/regions
    method: GET
    status_code: 200
    headers:
      Authorization: "Bearer {{ vultr_api_key }}"
  register: _vultr_regions

- name: Format regions
  set_fact:
    regions: "{{ _vultr_regions.json['regions'] }}"

- name: Set regions as a fact
  set_fact:
    vultr_regions: "{{ regions | sort(attribute='country') }}"

- name: Set default region
  set_fact:
    default_region: 1

- pause:
    prompt: |
      What region should the server be located in?
      (https://www.vultr.com/locations/):
        {% for r in vultr_regions %}
        {{ loop.index }}.   {{ r['city'] }} ({{ r['id'] }})
        {% endfor %}

      Enter the number of your desired region
      [{{ default_region }}]
  register: _algo_region
  when: region is undefined

- name: Set the desired region as a fact
  set_fact:
    algo_vultr_region: >-
      {%- if region is defined -%}{{ region }}{%-
      elif _algo_region.user_input -%}{{ vultr_regions[_algo_region.user_input | int - 1]['id'] }}{%-
      else -%}{{ vultr_regions[default_region | int - 1]['id'] }}{%-
      endif -%}
    algo_region: >-
      {%- if region is defined -%}{{ region }}{%-
      elif _algo_region.user_input -%}{{ vultr_regions[_algo_region.user_input | int - 1]['id'] }}{%-
      else -%}{{ vultr_regions[default_region | int - 1]['id'] }}{%-
      endif -%}
