#!/bin/bash

BT_VAR1=$(hwinfo --bluetooth | awk '/Hardware Class/ {print $3}')
BT_VAR2='bluetooth'
BT_REQUIRED_PKGS='bluetooth bluez libbluetooth-dev libudev-dev'
BT_REQUIRED_PKGS_CHK='bluetooth'

# Check the Bluetooth module version
# ┌─────────────────────────────────┐
# | HCI version | Bluetooth version |
# |-------------|-------------------|
# | 0 (0x0)     | 1.0b              |
# | 1 (0x1)     | 1.1               |
# | 2 (0x2)     | 1.2               |
# | 3 (0x3)     | 2.0               |
# | 4 (0x4)     | 2.1               |
# | 5 (0x5)     | 3.0               |
# | 6 (0x6)     | 4.0               |
# | 7 (0x7)     | 4.1               |
# | 8 (0x8)     | 4.2               |
# | 9 (0x9)     | 5.0               |
# | 10 (0xa)    | 5.1               |
# | 11 (0xb)    | 5.2               |
# | 12 (0xc)    | 5.3               |
# └─────────────────────────────────┘

if [ "$BT_VAR1" = "$BT_VAR2" ]; then
    BT_AVAILABLE='true'
    BT_REQUIRED_PKGS_OK=$(dpkg-query -W --showformat='${Status}\n' $BT_REQUIRED_PKGS | grep "install ok installed")
    if [ "" = "$BT_REQUIRED_PKGS_OK" ]; then
        BT_AVAILABLE='false'
    else
        BT_VERSION=$(hciconfig -a | awk 'NR==14 { print substr($3,1,9) }')
    fi
else
    BT_AVAILABLE='false'
fi

if [ "$BT_AVAILABLE" = 'true' ] && [ "$BT_VERSION" != '' ]; then
    printf "{\"bluetooth\":true}\n"
else
   printf "{\"bluetooth\":false}\n"
fi
