#!/bin/bash

list_devices() {
    adb devices | awk '/(^[[:alnum:]]+[[:blank:]]+device$)/ {print $1}'
}

first_device() {
    devices="$(adb devices | awk '/(^[[:alnum:]]+[[:blank:]]+device$)/ {print $1}')"
    if [ -z "$devices" ]
    then
        echo ""
        return
    else
        set -- "$devices"
        echo $1
    fi
}

has_devices() {
    [ ! -z "$(list_devices)" ] && return
    false
}

which adb >/dev/null 2>/dev/null
if [ $? != 0 ]
then
    echo "ADB not installed or not located in $PATH" >&2
    exit 4
fi

which scrcpy >/dev/null 2>/dev/null
if [ $? != 0 ]
then
    echo "scrcpy not installed or not located in $PATH" >&2
    exit 4
fi

declare -A serial_map
declare -A bluetooth_map

while true
do
    devices="$(list_devices)"
    while read serial;
    do
        if [ -z "$serial" ]
        then
            continue
        fi
        if [ -z "${serial_map[$serial]}" ]
        then
            echo "New device $serial connected" >&2
            scrcpy -s "$serial" &
            serial_map[$serial]=$!
            android-lock -u -s "$serial"
            # Link the phone to bluetooth as well.
            bluetooth_mac="$(adb -s "$serial" shell settings get secure bluetooth_address)"
            bluetoothctl devices | grep "$bluetooth_mac" >/dev/null 2>/dev/null
            if [ $? != 0 ]
            then
                # Pair the devices
                bluetoothctl scan on
                adb -s "$serial" shell am start -a android.bluetooth.adapter.action.REQUEST_DISCOVERABLE
                sleep 1
                bluetoothctl pair "$bluetooth_mac"
                bluetoothctl scan off
            else
                adb -s "$serial" shell am start -a android.bluetooth.adapter.action.REQUEST_ENABLE
            fi
            bluetoothctl connect "$bluetooth_mac"
            bluetooth_map[$serial]="$bluetooth_mac"
        fi
    done <<< "$devices"

    # Check for devices that have disconnected.
    for serial in "${!serial_map[@]}"
    do
        adb -s "$serial" get-state >/dev/null 2>/dev/null
        if [ $? != 0 ]
        then
            # The device has since been disconnected, and we should remove it.
            echo "Device $serial disconnected"
            kill "${serial_map[$serial]}"
            unset serial_map[$serial]
            echo "Disconnecting bluetooth ${bluetooth_map[$serial]}"
            bluetoothctl disconnect "${bluetooth_map[$serial]}"
            echo "Bluetooth disconnected"
            unset bluetooth_map[$serial]
        fi
    done
done
