---
- name: Deploy
  hosts: all

  tasks:
    - name: Ensure s3cmd is present
      ansible.builtin.apt:
        name: s3cmd
        update_cache: yes
        state: present
      become: yes

    - name: Configure s3cmd to utilize spaces credentials
      ansible.builtin.shell: "s3cmd --access_key='{{ spaces_access_key }}' --secret_key='{{ spaces_secret_key }}' --host-bucket='%(bucket)s.nyc3.digitaloceanspaces.com'  -s --no-encrypt --dump-config 2>&1 | tee .s3cfg"
   
    - name: Create artifact directory
      ansible.builtin.file:
        path: '/tmp/{{ version }}'
        state: directory
        mode: '0755'
      become: yes

    - name: Pull down artifact from DO Spaces
      # Update with DO Spaces endpoint
      ansible.builtin.shell: 's3cmd get s3://iservice-artifacts/iservice-customer-{{ version }}.tar'

    - name: Expand archive
      ansible.builtin.shell: 'tar -xvf iservice-customer-{{ version }}.tar -C /tmp/{{ version }}'
      become: yes

    - name: Remove existing files from webserver directory
      ansible.builtin.file:
        path: '{{ deployment_path }}/*'
        state: absent
      become: yes

    - name: Move files into webserver directory
      ansible.builtin.copy:
        src: '/tmp/{{ version }}/build/'
        dest: '{{ deployment_path }}'
        remote_src: yes
      become: yes
   
    - name: Remove artifact directory
      ansible.builtin.file:
        path: '/tmp/{{ version }}'
        state: absent
      become: yes
      
    - name: Remove artifact tar file
      ansible.builtin.file:
        path: 'iservice-customer-{{ version }}.tar'
        state: absent
      become: yes