#!/bin/bash

# omarchy:summary=Turn on BlueZ device privacy so Bluetooth LE controllers keep their pairing
# omarchy:requires-sudo=true
# omarchy:hidden=true

set -e

# Without host privacy, the kernel leaves the identity key (IRK and identity
# address) out of the keys it distributes when pairing over Bluetooth LE. Xbox
# Wireless Controllers on BLE firmware 5.x complete such a pairing but discard
# it: the light keeps flashing, and every reconnect fails with "PIN or Key
# Missing" until the controller is paired again. Windows, Android and SteamOS
# distribute the identity key, which is why the same controller works there.
# `Privacy = device` makes the kernel distribute it.
#
# Any explicit setting, off included, is someone's choice and is left alone:
# migrations run once per user, so replacing an `off` would undo it for the
# whole machine every time another account updates.

conf=/etc/bluetooth/main.conf

# --no-restart leaves the change for bluetoothd's next start instead of dropping live connections now.
restart=true
[[ ${1:-} == --no-restart ]] && restart=false

as_root() {
  if (( EUID == 0 )); then
    "$@"
  else
    sudo "$@"
  fi
}

# A restart that never happened (refused, or interrupted after the write) leaves
# the daemon on the old file; a later run finishes it.
daemon_predates_conf() {
  local started modified
  systemctl is-active --quiet bluetooth.service || return 1
  started=$(systemctl show bluetooth.service -p ActiveEnterTimestamp --value --timestamp=us+utc)
  [[ -n $started ]] || return 1
  started=$(LC_ALL=C date -d "$started" +%s%6N) || return 1
  modified=$(LC_ALL=C stat -L -c %.6Y "$conf")
  (( 10#$started < 10#${modified/./} ))
}

if [[ ! -f $conf ]]; then
  [[ ${1:-} == --check ]] && exit 1
  echo "No $conf to configure; skipping Bluetooth privacy."
  exit 0
fi

# A header is [General] only as written; BlueZ reads "[ General ]" as another group.
current=$(awk '
  /^[[:space:]]*\[/ { section = $0; gsub(/^[[:space:]]+|[[:space:]]+$/, "", section) }
  section == "[General]" && /^[[:space:]]*Privacy[[:space:]]*=/ {
    value = $0
    sub(/^[^=]*=[[:space:]]*/, "", value)
    sub(/[[:space:]]+$/, "", value)
  }
  END { print value }
' "$conf")

# --check answers whether privacy is decided and in effect, so the Xbox menu entry can offer it until then.
if [[ ${1:-} == --check ]]; then
  [[ -n $current ]] || exit 1
  [[ $current == "device" ]] && daemon_predates_conf && exit 1
  exit 0
fi

if [[ $current == "off" ]]; then
  echo "Bluetooth privacy is turned off in $conf; leaving it. Bluetooth LE Xbox controllers won't keep their pairing until it is set to device."
elif [[ -n $current ]]; then
  echo "Bluetooth privacy is already set ($current); leaving it."
  if $restart && [[ $current == "device" ]] && daemon_predates_conf; then
    as_root systemctl try-restart bluetooth.service
  fi
else
  echo "Enabling Bluetooth device privacy. Bluetooth LE devices paired before this may need pairing again."

  updated=$(awk '
    /^[[:space:]]*\[/ { section = $0; gsub(/^[[:space:]]+|[[:space:]]+$/, "", section) }
    section == "[General]" && /^[[:space:]]*Privacy[[:space:]]*=/ { next }
    { print }
    section == "[General]" && !added && /^[[:space:]]*\[/ {
      print "Privacy = device"
      added = 1
    }
    END { if (!added) printf "\n[General]\nPrivacy = device\n" }
  ' "$conf")

  # Write beside the real file and rename, so an interrupted write never
  # truncates main.conf and a symlinked one stays a symlink.
  target=$(readlink -f "$conf")
  staged=$(as_root mktemp "$target.XXXXXX")
  trap 'as_root rm -f -- "$staged"' EXIT
  as_root tee "$staged" >/dev/null <<<"$updated"
  as_root chmod --reference="$target" "$staged"
  as_root chown --reference="$target" "$staged"
  as_root mv -f "$staged" "$target"
  trap - EXIT

  # Only a running daemon needs the restart; an inactive one reads the file
  # when it starts.
  if $restart; then
    as_root systemctl try-restart bluetooth.service
  else
    echo "It takes effect the next time Bluetooth starts, after a reboot at the latest."
  fi
fi
