---
- name: Include prompts
  import_tasks: prompts.yml

- environment:
    VULTR_API_KEY: "{{ lookup('ini', 'key', section='default', file=algo_vultr_config) }}"
  block:
    - name: Set cloud-init script as fact
      set_fact:
        algo_cloud_init_script: "{{ lookup('template', 'files/cloud-init/base.yml') }}"

    - name: Creating a firewall group
      vultr.cloud.firewall_group:
        name: "{{ algo_server_name }}"

    - name: Creating firewall rules
      vultr.cloud.firewall_rule:
        group: "{{ algo_server_name }}"
        protocol: "{{ item.protocol }}"
        port: "{{ item.port }}"
        ip_type: "{{ item.ip }}"
        subnet: "{{ item.cidr.split('/')[0] }}"
        subnet_size: "{{ item.cidr.split('/')[1] }}"
      loop:
        - { protocol: tcp, port: "{{ ssh_port }}", ip: v4, cidr: 0.0.0.0/0 }
        - { protocol: tcp, port: "{{ ssh_port }}", ip: v6, cidr: "::/0" }
        - { protocol: udp, port: 500, ip: v4, cidr: 0.0.0.0/0 }
        - { protocol: udp, port: 500, ip: v6, cidr: "::/0" }
        - { protocol: udp, port: 4500, ip: v4, cidr: 0.0.0.0/0 }
        - { protocol: udp, port: 4500, ip: v6, cidr: "::/0" }
        - { protocol: udp, port: "{{ wireguard_port }}", ip: v4, cidr: 0.0.0.0/0 }
        - { protocol: udp, port: "{{ wireguard_port }}", ip: v6, cidr: "::/0" }

    - name: Upload the startup script
      vultr.cloud.startup_script:
        name: algo-startup
        script: "{{ algo_cloud_init_script }}"

    - name: Creating a server
      vultr.cloud.instance:
        name: "{{ algo_server_name }}"
        startup_script: algo-startup
        hostname: "{{ algo_server_name }}"
        os: "{{ cloud_providers.vultr.os }}"
        plan: "{{ cloud_providers.vultr.size }}"
        region: "{{ algo_vultr_region }}"
        firewall_group: "{{ algo_server_name }}"
        state: started
        tags:
          - Environment:Algo
        enable_ipv6: true
        backups: false
        activation_email: false
      register: vultr_server

    - set_fact:
        cloud_instance_ip: "{{ vultr_server.vultr_instance.main_ip }}"
        ansible_ssh_user: algo
        ansible_ssh_port: "{{ ssh_port }}"
        cloudinit: true
