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

- environment:
    SCW_TOKEN: "{{ algo_scaleway_token }}"
  block:
    - name: Get Ubuntu 22.04 image ID from Scaleway Marketplace API
      uri:
        url: "https://api-marketplace.scaleway.com/images?arch={{ cloud_providers.scaleway.arch }}&include_eol=false"
        method: GET
        return_content: true
      register: marketplace_images

    - name: Find Ubuntu 22.04 Jammy image
      set_fact:
        scaleway_image_id: >-
          {{ (marketplace_images.json.images |
              selectattr('name', 'match', '.*Ubuntu.*22\\.04.*Jammy.*') |
              first).versions[0].local_images |
              selectattr('zone', 'equalto', algo_region) |
              map(attribute='id') | first }}

    - name: Create a server
      scaleway_compute:
        name: "{{ algo_server_name }}"
        enable_ipv6: true
        public_ip: dynamic
        boot_type: local
        state: present
        image: "{{ scaleway_image_id }}"
        project: "{{ algo_scaleway_org_id }}"
        region: "{{ algo_region }}"
        commercial_type: "{{ cloud_providers.scaleway.size }}"
        wait: true
        tags:
          - Environment:Algo
          - AUTHORIZED_KEY={{ lookup('file', SSH_keys.public) | regex_replace(' ', '_') }}
      register: scaleway_compute

    - name: Patch the cloud-init
      uri:
        url: https://cp-{{ algo_region }}.scaleway.com/servers/{{ scaleway_compute.msg.id }}/user_data/cloud-init
        method: PATCH
        body: "{{ lookup('template', 'files/cloud-init/base.yml') }}"
        status_code: 204
        headers:
          Content-Type: text/plain
          X-Auth-Token: "{{ algo_scaleway_token }}"

    - name: Start the server
      scaleway_compute:
        name: "{{ algo_server_name }}"
        enable_ipv6: true
        public_ip: dynamic
        boot_type: local
        state: running
        image: "{{ scaleway_image_id }}"
        project: "{{ algo_scaleway_org_id }}"
        region: "{{ algo_region }}"
        commercial_type: "{{ cloud_providers.scaleway.size }}"
        wait: true
        tags:
          - Environment:Algo
          - AUTHORIZED_KEY={{ lookup('file', SSH_keys.public) | regex_replace(' ', '_') }}
      register: algo_instance
      until: algo_instance.msg.public_ip
      retries: 3
      delay: 3

- set_fact:
    cloud_instance_ip: "{{ algo_instance.msg.public_ip.address }}"
    ansible_ssh_user: algo
    ansible_ssh_port: "{{ ssh_port }}"
    cloudinit: true
