#!/usr/bin/env bash
set -Eeuo pipefail

if [[ ${EUID} -ne 0 ]]; then
  echo "The Bluetooth control helper must run as root." >&2
  exit 1
fi

BLUETOOTHCTL=/usr/bin/bluetoothctl
SYSTEMCTL=/usr/bin/systemctl
BRIDGE_SERVICE=pi-car-companion-bluetooth.service

print_status() {
  local details powered discoverable pairable message
  details="$(LC_ALL=C "${BLUETOOTHCTL}" show 2>/dev/null || true)"
  if ! grep -q '^Controller ' <<<"${details}"; then
    printf '%s\n' '{"supported":false,"powered":false,"discoverable":false,"pairable":false,"message":"No Bluetooth adapter was found."}'
    return
  fi
  powered="$(sed -n 's/^[[:space:]]*Powered: //p' <<<"${details}" | head -n 1)"
  discoverable="$(sed -n 's/^[[:space:]]*Discoverable: //p' <<<"${details}" | head -n 1)"
  pairable="$(sed -n 's/^[[:space:]]*Pairable: //p' <<<"${details}" | head -n 1)"
  [[ "${powered}" == "yes" ]] && powered=true || powered=false
  [[ "${discoverable}" == "yes" ]] && discoverable=true || discoverable=false
  [[ "${pairable}" == "yes" ]] && pairable=true || pairable=false
  if [[ "${discoverable}" == "true" ]]; then
    message="The Pi is visible to nearby phones for three minutes."
  elif [[ "${powered}" == "true" ]]; then
    message="Bluetooth is on and the companion bridge is available."
  else
    message="Bluetooth is off."
  fi
  printf '{"supported":true,"powered":%s,"discoverable":%s,"pairable":%s,"message":"%s"}\n' \
    "${powered}" "${discoverable}" "${pairable}" "${message}"
}

power_on() {
  "${SYSTEMCTL}" start bluetooth.service
  /usr/sbin/rfkill unblock bluetooth
  "${BLUETOOTHCTL}" power on >/dev/null
  "${SYSTEMCTL}" enable --now "${BRIDGE_SERVICE}" >/dev/null
}

case "${1:-}" in
  status)
    ;;
  on)
    power_on
    ;;
  off)
    "${SYSTEMCTL}" disable --now "${BRIDGE_SERVICE}" >/dev/null
    "${BLUETOOTHCTL}" discoverable off >/dev/null 2>&1 || true
    "${BLUETOOTHCTL}" pairable off >/dev/null 2>&1 || true
    "${BLUETOOTHCTL}" power off >/dev/null
    /usr/sbin/rfkill block bluetooth
    ;;
  discoverable)
    power_on
    "${BLUETOOTHCTL}" discoverable-timeout 180 >/dev/null
    "${BLUETOOTHCTL}" discoverable on >/dev/null
    ;;
  *)
    echo "Usage: pi-car-companion-bluetooth-control status|on|off|discoverable" >&2
    exit 2
    ;;
esac

print_status
