---
# Linux-specific Tailscale installation (Debian/Ubuntu)

- name: Add Tailscale GPG key
  ansible.builtin.shell:
    cmd: |
      set -o pipefail
      DIST="{{ ansible_distribution | lower }}"
      RELEASE="{{ ansible_distribution_release }}"
      curl -fsSL "https://pkgs.tailscale.com/stable/${DIST}/${RELEASE}.noarmor.gpg" | \
        tee /usr/share/keyrings/tailscale-archive-keyring.gpg > /dev/null
    creates: /usr/share/keyrings/tailscale-archive-keyring.gpg
    executable: /bin/bash

- name: Add Tailscale repository
  ansible.builtin.shell:
    cmd: |
      set -o pipefail
      DIST="{{ ansible_distribution | lower }}"
      RELEASE="{{ ansible_distribution_release }}"
      curl -fsSL "https://pkgs.tailscale.com/stable/${DIST}/${RELEASE}.tailscale-keyring.list" | \
        tee /etc/apt/sources.list.d/tailscale.list > /dev/null
    creates: /etc/apt/sources.list.d/tailscale.list
    executable: /bin/bash

- name: Update apt cache after adding Tailscale repo
  ansible.builtin.apt:
    update_cache: true

- name: Install Tailscale
  ansible.builtin.apt:
    name: tailscale
    state: present

- name: Enable Tailscale service (Linux)
  ansible.builtin.systemd:
    name: tailscaled
    enabled: true
    state: started

- name: Check if Tailscale is already connected (Linux)
  ansible.builtin.command: tailscale status --json
  register: tailscale_status_linux
  changed_when: false
  failed_when: false

- name: Display Tailscale auth URL if not connected (Linux)
  ansible.builtin.debug:
    msg:
      - "============================================"
      - "Tailscale installed but not connected yet"
      - "============================================"
      - ""
      - "To connect this machine to your Tailnet:"
      - "Run: sudo tailscale up"
      - ""
      - "For unattended installation, use an auth key:"
      - "sudo tailscale up --authkey tskey-auth-xxxxx"
      - ""
      - "Get auth key from: https://login.tailscale.com/admin/settings/keys"
  when: tailscale_status_linux.rc != 0
