---
- name: Ensure additional dependencies are installed (on Ubuntu < 20.04 and any other systems).
  ansible.builtin.apt:
    name: gnupg2
    state: present
  when: ansible_distribution != 'Ubuntu' or ansible_distribution_version is version('20.04', '<')
  become: true

- name: Ensure additional dependencies are installed (on Ubuntu >= 20.04).
  ansible.builtin.apt:
    name: gnupg
    state: present
  when: ansible_distribution == 'Ubuntu' or ansible_distribution_version is version('20.04', '>=')
  become: true

- name: Add tailscale apt key.
  ansible.builtin.apt_key:
    url: "{{ tailscale_apt_gpg_key }}"
    state: present
  become: true

- name: Add tailscale apt repository.
  ansible.builtin.apt_repository:
    repo: "{{ tailscale_apt_repository }}"
    state: present
    update_cache: true
  become: true

- name: Install tailscale
  ansible.builtin.apt:
    pkg:
      - tailscale
  become: true

- name: Create user
  ansible.builtin.shell: "headscale user create {{ username }}"
  become: true
  delegate_to: "{{ headscale_server_ip }}"
  tags:
    - skip_ansible_lint

- name: Create pre-auth key
  ansible.builtin.shell: "headscale preauthkeys create --reusable -e 1h --user {{ username }}"
  become: true
  delegate_to: "{{ headscale_server_ip }}"
  tags:
    - skip_ansible_lint
  register: result

- name: Tailscale up
  ansible.builtin.shell: "tailscale up --login-server={{ headscale_domain }} --auth-key={{ result.stdout.split('\n')[-1] }} --ssh --reset"
  tags:
    - skip_ansible_lint
  become: true
