---
# Playbook 04: Tailscale Setup
# Install and optionally activate Tailscale VPN

- name: Tailscale Installation
  hosts: all
  become: yes
  
  tasks:
    - name: Add Tailscale GPG key
      apt_key:
        url: https://pkgs.tailscale.com/stable/ubuntu/{{ ansible_distribution_release }}.noarmor.gpg
        state: present

    - name: Add Tailscale repository
      apt_repository:
        repo: "deb https://pkgs.tailscale.com/stable/ubuntu {{ ansible_distribution_release }} main"
        state: present

    - name: Install Tailscale
      apt:
        name: tailscale
        state: present
        update_cache: yes

    - name: Check if Tailscale auth key is provided
      set_fact:
        tailscale_auto_enable: "{{ tailscale_auth_key is defined and tailscale_auth_key != '' }}"

    - name: Activate Tailscale (if auth key provided)
      command: tailscale up --authkey={{ tailscale_auth_key }} --advertise-tags=tag:nextcloud
      when: tailscale_auto_enable
      register: tailscale_activation

    - name: Get Tailscale IP (if activated)
      command: tailscale ip -4
      register: tailscale_ip
      when: tailscale_auto_enable
      changed_when: false

    - name: Display Tailscale status (activated)
      debug:
        msg: |
          ✓ Tailscale activated
          IP: {{ tailscale_ip.stdout }}
      when: tailscale_auto_enable

    - name: Display manual activation instructions (not activated)
      debug:
        msg: |
          Tailscale installed but not activated.
          To enable, run on the server:
          sudo tailscale up
      when: not tailscale_auto_enable

    - name: Enable Tailscale service
      service:
        name: tailscaled
        state: started
        enabled: yes
