---
# Discover AWS credentials from standard locations
- name: Set AWS credentials file path
  set_fact:
    aws_credentials_path: "{{ lookup('env', 'AWS_SHARED_CREDENTIALS_FILE') | default(lookup('env', 'HOME') + '/.aws/credentials', true) }}"
    aws_profile: "{{ lookup('env', 'AWS_PROFILE') | default('default', true) }}"

# Try to read credentials from file if not already provided
- block:
    - name: Check if AWS credentials file exists
      stat:
        path: "{{ aws_credentials_path }}"
      register: aws_creds_file
      delegate_to: localhost

    - name: Read AWS credentials from file
      set_fact:
        _file_access_key: "{{ lookup('ini', 'aws_access_key_id', section=aws_profile, file=aws_credentials_path, errors='ignore') | default('', true) }}"
        _file_secret_key: "{{ lookup('ini', 'aws_secret_access_key', section=aws_profile, file=aws_credentials_path, errors='ignore') | default('', true) }}"
        _file_session_token: "{{ lookup('ini', 'aws_session_token', section=aws_profile, file=aws_credentials_path, errors='ignore') | default('', true) }}"
      when: aws_creds_file.stat.exists
      no_log: true
  when:
    - aws_access_key is undefined
    - lookup('env', 'AWS_ACCESS_KEY_ID')|length <= 0

# Prompt for credentials if still not available
- pause:
    prompt: |
      Enter your AWS Access Key ID (http://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html)
      Note: Make sure to use an IAM user with an acceptable policy attached (see https://github.com/trailofbits/algo/blob/master/docs/deploy-from-ansible.md)
    echo: false
  register: _aws_access_key
  when:
    - aws_access_key is undefined
    - lookup('env', 'AWS_ACCESS_KEY_ID')|length <= 0
    - _file_access_key is undefined or _file_access_key|length <= 0

- pause:
    prompt: |
      Enter your AWS Secret Access Key (http://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html)
    echo: false
  register: _aws_secret_key
  when:
    - aws_secret_key is undefined
    - lookup('env', 'AWS_SECRET_ACCESS_KEY')|length <= 0
    - _file_secret_key is undefined or _file_secret_key|length <= 0

# Set final credentials with proper precedence
- set_fact:
    access_key: >-
      {{ aws_access_key
         | default(lookup('env', 'AWS_ACCESS_KEY_ID'))
         | default(_file_access_key)
         | default(_aws_access_key.user_input | default(None)) }}
    secret_key: >-
      {{ aws_secret_key
         | default(lookup('env', 'AWS_SECRET_ACCESS_KEY'))
         | default(_file_secret_key)
         | default(_aws_secret_key.user_input | default(None)) }}
    session_token: >-
      {{ aws_session_token
         | default(lookup('env', 'AWS_SESSION_TOKEN'))
         | default(_file_session_token)
         | default('') }}
  no_log: true

- block:
    - name: Get regions
      aws_region_info:
        aws_access_key: "{{ access_key }}"
        aws_secret_key: "{{ secret_key }}"
        aws_session_token: "{{ session_token if session_token else omit }}"
        region: us-east-1
      register: _aws_regions
      no_log: true

    - name: Set facts about the regions
      set_fact:
        aws_regions: "{{ _aws_regions.regions | sort(attribute='region_name') }}"

    - name: Set the default region
      set_fact:
        default_region: >-
          {% for r in aws_regions %}
          {%- if r['region_name'] == "us-east-1" %}{{ loop.index }}{% endif %}
          {%- endfor %}

    - pause:
        prompt: |
          What region should the server be located in?
          (https://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region)
            {% for r in aws_regions %}
            {{ loop.index }}. {{ r['region_name'] }}
            {% endfor %}

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

- name: Set algo_region and stack_name facts
  set_fact:
    algo_region: >-
      {% if region is defined %}{{ region }}
      {%- elif _algo_region.user_input %}{{ aws_regions[_algo_region.user_input | int -1 ]['region_name'] }}
      {%- else %}{{ aws_regions[default_region | int - 1]['region_name'] }}{% endif %}
    stack_name: "{{ algo_server_name | replace('.', '-') }}"

- block:
    - name: Get existing available Elastic IPs
      ec2_eip_info:
        aws_access_key: "{{ access_key }}"
        aws_secret_key: "{{ secret_key }}"
        aws_session_token: "{{ session_token if session_token else omit }}"
        region: "{{ algo_region }}"
      register: raw_eip_addresses
      no_log: true

    - set_fact:
        available_eip_addresses: "{{ raw_eip_addresses.addresses | selectattr('association_id', 'undefined') | list }}"

    - pause:
        prompt: >-
          What Elastic IP would you like to use?
            {% for eip in available_eip_addresses %}
            {{ loop.index }}. {{ eip['public_ip'] }}
            {% endfor %}

          Enter the number of your desired Elastic IP
      register: _use_existing_eip

    - set_fact:
        existing_eip: "{{ available_eip_addresses[_use_existing_eip.user_input | int -1 ]['allocation_id'] }}"
  when: cloud_providers.ec2.use_existing_eip
