---
- name: Check whether Tor Browser is already installed
  become: true
  ansible.builtin.stat:
    path: "~{{ local_username }}/.local/share/tor-browser/start-tor-browser.desktop"
  register: _torbrowser_stat

- name: Install Tor Browser
  when: not _torbrowser_stat.stat.exists
  block:
    - name: Create temp dir
      ansible.builtin.tempfile:
        state: directory
      register: _torbrowser_tempdir

    - name: Download and unpack distribution archive
      ansible.builtin.unarchive:
        src: https://dist.torproject.org/torbrowser/11.0.10/tor-browser-linux64-11.0.10_en-US.tar.xz
        remote_src: true
        dest: "{{ _torbrowser_tempdir.path }}"

    - name: Ensure ~/.local/share/ exists
      become: true
      ansible.builtin.file:
        path: ~{{ local_username }}/.local/share
        state: directory
        owner: "{{ local_username }}"
        group: "{{ local_username }}"
        mode: 0700

    - name: Copy Tor Browser distribution to ~/.local/share/
      become: true
      ansible.builtin.copy:
        remote_src: true
        src: "{{ _torbrowser_tempdir.path }}/tor-browser_en-US/"
        dest: "~{{ local_username }}/.local/share/tor-browser"
        owner: "{{ local_username }}"
        group: "{{ local_username }}"
        mode: 0700

    - name: Register application
      become: true
      become_user: "{{ local_username }}"
      changed_when: true
      ansible.builtin.command:
        cmd: ./start-tor-browser.desktop
        chdir: ~{{ local_username }}/.local/share/tor-browser

  always:
    - name: Delete temp dir
      ansible.builtin.file:
        path: "{{ _torbrowser_tempdir.path }}"
        state: absent
