---
- name: Set up mattermost
  hosts: localhost
  vars:
    uid: "{{ lookup('env','USER') }}"
    mattermost_url: "{{ lookup('ansible.builtin.pipe','../scripts/get_mattermost_url.sh') }}"
  connection: local
  become: false
  tasks:
    - name: Have mattermost allready installed
      stat:
        path: /usr/local/bin/mattermost-desktop
      register: have_mattermost
    - name: Download mattermost package
      ansible.builtin.command:
        chdir: /tmp
        cmd: wget "{{ mattermost_url }}" -O mattermost.tar.gz 
      when: not have_mattermost.stat.exists
    - name: Unpack mattermost package
      ansible.builtin.command:
        chdir: /tmp
        cmd: tar -xzf mattermost.tar.gz 
      when: not have_mattermost.stat.exists
    - name: Install mattermost package to /opt/mattermost
      ansible.builtin.command:
        chdir: /tmp
        cmd: bash -c "mv mattermost-desktop-* /opt/mattermost-desktop"
        creates: /opt/mattermost-desktop
      become: true
      when: not have_mattermost.stat.exists
    - name: install mattermost desktop link
      ansible.builtin.file:
        src: /opt/mattermost-desktop/mattermost-desktop
        dest: /usr/local/bin/mattermost-desktop
        state: link
      become: true
      when: not have_mattermost.stat.exists
    - name: install mattermost desktop file
      ansible.builtin.template:
        src: ../templates/mattermost-desktop.desktop.j2
        dest: /home/{{ uid }}/.local/share/applications/mattermost-desktop.desktop
        owner: '{{ uid }}'
        group: '{{ uid }}'
        mode: '0644'
      when: not have_mattermost.stat.exists
    - name: cleanup
      ansible.builtin.command:
        cmd: rm /tmp/mattermost.tar.gz
      when: not have_mattermost.stat.exists
