---

- name: Configure the Bluetooth service
  tags:
    - bluetooth
    - config
    - configuration
    - configure
    - daemon
    - daemons
    - service
    - services
    - tune
    - tuning
  hosts: all
  vars:
    auto_enable: true
    fast_connectable: true
  handlers:
    - name: Restart Bluez
      ansible.builtin.service:
        name: bluetooth.service
        state: restarted
  tasks:
    - name: Configure Bluetooth on Linux systems
      when: ansible_system == 'Linux'
      tags: linux
      block:
        - name: Configure how long to stay in discoverable mode before going back to non-discoverable
          tags: discoverable_timeout
          when: discoverable_timeout is defined
          become: true
          notify: Restart Bluez
          ansible.builtin.lineinfile:
            path: "/etc/bluetooth/main.conf"
            line: "DiscoverableTimeout = {{ discoverable_timeout | string | lower }}"
            regexp: '^.*DiscoverableTimeout\s*=\s*.*$'
            insertafter: '^[General]$'
            mode: '0644'
            create: true
            backup: true
        - name: Configure faster Bluetooth connection to devices
          tags: fast_connectable
          when: fast_connectable is defined
          become: true
          notify: Restart Bluez
          ansible.builtin.lineinfile:
            path: "/etc/bluetooth/main.conf"
            line: "FastConnectable = {{ fast_connectable | string | lower }}"
            regexp: '^.*FastConnectable\s*=\s*.*$'
            insertafter: '^[General]$'
            mode: '0644'
            create: true
            backup: true
        - name: Configure the default adapter's name
          tags: name
          when: name is defined
          become: true
          notify: Restart Bluez
          ansible.builtin.lineinfile:
            path: "/etc/bluetooth/main.conf"
            line: "Name = {{ name | string | lower }}"
            regexp: '^.*Name\s*=\s*.*$'
            insertafter: '^[General]$'
            mode: '0644'
            create: true
            backup: true
        - name: Enable Bluetooth adapters as soon as they are found
          tags: auto_enable
          when: auto_enable is defined
          become: true
          notify: Restart Bluez
          ansible.builtin.lineinfile:
            path: "/etc/bluetooth/main.conf"
            line: "AutoEnable = {{ auto_enable | string | lower }}"
            regexp: '^.*AutoEnable\s*=\s*.*$'
            insertafter: '^[Policy]$'
            mode: '0644'
            create: true
            backup: true
