#!/bin/bash

start_restart_reboot() (

  (( trial_count = 0 ))
  while ! dotpi audio_bluetooth_destination_start ; do
      (( ++trial_count ))
      dotpi echo_info "Try to start audio bluetooth: attempt ${trial_count}."

      hci_up="$(hciconfig hci0 | grep 'UP' | wc -l)"
      if (( $? != 0 ))  || (( hci_up == 0 )) ; then
        dotpi echo_error "Bluetooth device is down."
        dotpi echo_warning "Try to reset bluetooth device."
        sudo hciconfig hci0 reset || {
          dotpi echo_error "Failed to reset bluetooth device."
          dotpi echo_warning "Rebooting system."
          sudo reboot
        }
        sleep 20
      fi

      if (( trial_count >=9 )) ; then
        dotpi echo_error "Failed to start audio bluetooth destination."
        dotpi echo_warning "Rebooting system."
        sudo reboot
      fi

      if (( trial_count == 6 )) ; then

        sudo hciconfig hci0 reset || {
          dotpi echo_error "Failed to reset bluetooth device."
          dotpi echo_warning "Rebooting system."
          sudo reboot
        }

        sleep 20
      fi

      if (( trial_count == 3  || trial_count == 6)) ; then
        sleep 10
        dotpi echo_warning "Stopping audio bluetooth destination."
        dotpi audio_bluetooth_destination_stop
      fi

      sleep 10
      dotpi echo_warning "Starting audio bluetooth destination again."
  done

  local_file="$(dotpi_readlink_follow "$0")"
  local_path="$(dirname -- "$local_file")"
  FIRSTUSER="$(getent passwd 1000 | cut -d: -f1)"
  # execute in a proper user session for pipewire to work
  sudo machinectl shell "${FIRSTUSER}@" /bin/bash -c "(
    (( trial_count = 0 ))
    while (( trial_count < 10 )) ; do
      '${local_path}/dotpi_audio_pipewire_relink' && exit 0
      sleep 3
      (( ++trial_count ))
    done
    sudo reboot
  )"

)

source /opt/dotpi/share/dotpi_init.bash

dotpi echo_info "############ Start command"
clean_up() {
  if [[ -n ${btctl_process_PID} ]] ; then
      dotpi echo_info "########### clean_up"
      dotpi echo_info "Ending bluetoothctl process ${btctl_process_PID}"
      kill "${btctl_process_PID}"
      dotpi echo_info "Stopping audio bluetooth destination"
      sudo dotpi audio_bluetooth_destination_stop
  fi
}
trap clean_up HUP TERM INT

destination_mac="${dotpi_audio_bluetooth_mac}"
destination_descriptor="${dotpi_audio_bluetooth_mac//:/_}"

# dotpi echo_info "Stopping audio bluetooth destination"
# sudo dotpi audio_bluetooth_destination_stop

dotpi echo_info "Starting bluetoothctl monitor process"
coproc btctl_process { bluetoothctl; }

dotpi echo_info "Starting audio bluetooth destination"

start_restart_reboot

status='init'
dotpi echo_warning "status: $status"
while IFS= read -r output ; do
    echo "$output" >&2

    # destination disconnected

    if [[ "$output" =~ [DEL].*Endpoint.*/org/bluez/.*dev_"${destination_descriptor}" ]] ; then
        # connect again
        dotpi echo_error "Audio bluetooth destination (${destination_mac}) disconnected."
        dotpi echo_info "Connecting again"

        sleep 2

        start_restart_reboot

    fi

    # if [[ "$status" == "init" ]] \
    #     && [[ "$output" =~ [DEL].*Endpoint.*/org/bluez/.*dev_"${destination_descriptor}" ]] ; then
    #     status='deleted'
    #     dotpi echo_warning "status: $status"
    # fi

    # if [[ "$status" == "deleted" ]] \
    #     && [[ "$output" =~ [CHG].*Device.*"${destination_mac}".*Connected:.*no ]] ; then

    #     # connect again
    #     dotpi echo_error "Audio bluetooth destination (${destination_mac}) disconnected."
    #     dotpi echo_info "Connecting again"

    #     status='init'
    #     dotpi echo_warning "status: $status"

    #     dotpi audio_bluetooth_destination_start
    # fi

done <&${btctl_process[0]}

dotpi echo_info "############ Start ending"

dotpi echo_info "Stopping audio bluetooth destination"
dotpi audio_bluetooth_destination_stop
