---
- name: store s3_deploy secret access key
  set_fact:
    aws_secret_key: "{{ lookup('file', 'files/s3_deploy_secret_access_key') }}"

- name: clone safe_network repo
  ansible.builtin.git:
    repo: https://github.com/{{ org }}/safe_network
    version: "{{ branch }}"
    dest: "{{ ansible_env.HOME }}/safe_network"

# only enable safenode features
- name: "build {{ bin_name }} binary"
  ansible.builtin.shell: |
    source $HOME/.cargo/env
    {% if protocol_version is defined and protocol_version != "" %}
    export NETWORK_VERSION_MODE={{ protocol_version }}
    {% endif %}

    {% if chunk_size is defined and chunk_size != "" %}
    export MAX_CHUNK_SIZE={{ chunk_size }}
    {% endif %}

    {% if foundation_pk is defined and foundation_pk != "" %}
    export FOUNDATION_PK={{ foundation_pk }}
    {% endif %}
    {% if genesis_pk is defined and genesis_pk != "" %}
    export GENESIS_PK={{ genesis_pk }}
    {% endif %}
    {% if network_royalties_pk is defined and network_royalties_pk != "" %}
    export NETWORK_ROYALTIES_PK={{ network_royalties_pk }}
    {% endif %}
    {% if payment_forward_pk is defined and payment_forward_pk != "" %}
    export PAYMENT_FORWARD_PK={{ payment_forward_pk }}
    {% endif %}

    {% if bin_name == 'safenode' and safenode_features_list != "" %}
    cargo build --target x86_64-unknown-linux-musl --release --bin {{bin_name}} --no-default-features --features={{safenode_features_list}}
    {% elif bin_name == 'faucet' %}
    cargo build --target x86_64-unknown-linux-musl --release --bin {{bin_name}} --features="distribution"
    {% else %}
    cargo build --target x86_64-unknown-linux-musl --release --bin {{bin_name}}
    {% endif %}
  args:
    chdir: "{{ ansible_env.HOME }}/safe_network"
    creates: "{{ ansible_env.HOME }}/safe_network/target/x86_64-unknown-linux-musl/release/{{bin_name}}"
    executable: /bin/bash

- name: copy binary to tmp directory
  ansible.builtin.command:
    chdir: "{{ ansible_env.HOME }}/safe_network/target/x86_64-unknown-linux-musl/release"
    cmd: cp {{bin_name}} /tmp/

- name: archive binary
  ansible.builtin.command:
    chdir: /tmp/
    cmd: tar -zcvf {{ bin_archive_filename }} {{ bin_name }}

# Uploads the archive to "https://sn-node.s3.eu-west-2.amazonaws.com/{org}/{branch}/{bin_name}-{testnet_name}-x86_64-unknown-linux-musl.tar.gz",
- name: upload archive to S3
  amazon.aws.s3_object:
    access_key: AKIAVVODCRMSJUNFO3E5
    secret_key: "{{ aws_secret_key }}"
    bucket: sn-node
    object: /{{ org }}/{{ branch }}/{{ bin_archive_filename }}
    src: /tmp/{{ bin_archive_filename }}
    mode: put
    permission: public-read
