#!/bin/bash 

# Copyright Jean-Philippe Guillemin <h1p8r10n@yandex.com>. This program is free software;
# you can redistribute it and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version. Please take a look at http://www.gnu.org/copyleft/gpl.htm


case $1 in
	'up')
		# wait for BT
		until pidof bluetoothd 1>/dev/null --check ; do sleep 1; done

		# wait for PW
		until killall -0 pipewire ; do sleep 1 ; done
		
		sleep 1
		bluetoothctl power on
		
		# Connect the last connected
		for device in $(cat $HOME/.last-bt-devices) ; do 
			bluetoothctl connect $device 
		done
		## Or connect the first trusted
		#for i in $( bluetoothctl devices | cut -f2 -d " " ); do 
			#bluetoothctl info "$i" | grep -q "Trusted: yes" && bluetoothctl connect "$i" && exit
		#done
		
		## Or connect the first in listof paired
		#for i in $( bluetoothctl devices | cut -f2 -d " " ); do 
			#bluetoothctl info "$i" && bluetoothctl connect "$i" && exit
		#done
		;;
	'save')
		rm -f $HOME/.last-bt-devices
		for i in $( bluetoothctl devices | cut -f2 -d " " ); do 
			bluetoothctl info "$i" | grep -q "Connected: yes" && echo "$i" >> $HOME/.last-bt-devices 
		done
		;;
	'down')
		for i in $( bluetoothctl devices | cut -f2 -d " " ); do 
			bluetoothctl disconnect "$i" 
		done
		;;
esac



