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

- environment:
    CLOUDSTACK_KEY: "{{ algo_cs_key }}"
    CLOUDSTACK_SECRET: "{{ algo_cs_token }}"
    CLOUDSTACK_ENDPOINT: "{{ algo_cs_url }}"
  no_log: true
  block:
    - set_fact:
        algo_region: >-
          {%- if region is defined -%}{{ region }}{%-
          elif _algo_region.user_input is defined and _algo_region.user_input | length > 0 -%}{{ cs_zones[_algo_region.user_input | int - 1]['name'] }}{%-
          else -%}{{ cs_zones[default_zone | int - 1]['name'] }}{%-
          endif -%}

    - name: Security group created
      cs_securitygroup:
        name: "{{ algo_server_name }}-security_group"
        description: AlgoVPN security group
      register: cs_security_group

    - name: Security rules created
      cs_securitygroup_rule:
        security_group: "{{ cs_security_group.name }}"
        protocol: "{{ item.proto }}"
        start_port: "{{ item.start_port }}"
        end_port: "{{ item.end_port }}"
        cidr: "{{ item.range }}"
      loop:
        - { proto: tcp, start_port: "{{ ssh_port }}", end_port: "{{ ssh_port }}", range: 0.0.0.0/0 }
        - { proto: udp, start_port: 4500, end_port: 4500, range: 0.0.0.0/0 }
        - { proto: udp, start_port: 500, end_port: 500, range: 0.0.0.0/0 }
        - { proto: udp, start_port: "{{ wireguard_port }}", end_port: "{{ wireguard_port }}", range: 0.0.0.0/0 }

    - name: Set facts
      set_fact:
        image_id: "{{ cloud_providers.cloudstack.image }}"
        size: "{{ cloud_providers.cloudstack.size }}"
        disk: "{{ cloud_providers.cloudstack.disk }}"

    - name: Server created
      cs_instance:
        name: "{{ algo_server_name }}"
        root_disk_size: "{{ disk }}"
        template: "{{ image_id }}"
        security_groups: "{{ cs_security_group.name }}"
        zone: "{{ algo_region }}"
        service_offering: "{{ size }}"
        user_data: "{{ lookup('template', 'files/cloud-init/base.yml') }}"
      register: cs_server

    - set_fact:
        cloud_instance_ip: "{{ cs_server.default_ip }}"
        ansible_ssh_user: algo
        ansible_ssh_port: "{{ ssh_port }}"
        cloudinit: true
