#!/bin/sh

load() {
	device=$(adb devices | sed '/^\*/d;/^List of devices/d;/^$/d' | cut -f1 | fzf -1)
	[ -z "$device" ] && printf "Unable to detect Android using ADB" && exit 1
	RES=$(adb -s "$device" shell dumpsys display | sed -nE 's|^[[:space:]]*DisplayModeRecord.*width=([0-9]*), height=([0-9]*), fps=([0-9\.]*).*|\2x\1@\3|p' | fzf --prompt="Select Resolution > " -1)
	position=$(printf 'auto\nauto-left' | fzf --prompt="Which position? >")
	if ! hyprctl monitors | grep -q "$HEADLESS"; then
		hyprctl output create headless "$HEADLESS" | grep -q 'ok' && printf '\n\nCreate Headless Display: %s' "$HEADLESS"
	fi
	[ -z "$HEADLESS" ] && printf "Something went wrong\n" && return 1
	hyprctl keyword monitor "$HEADLESS","$RES","$position",'1'

	adb shell svc usb setFunctions rndis
	printf "Sleep 2 seconds for USB tethering Interface to be UP and connected/"
	sleep 2

	# show ip
	ip r

	# start sunshine
	sunshine >/dev/null
}

unload() {
	hyprctl output remove "$HEADLESS"
}

HEADLESS="HEADLESS-ANDROID"

trap 'unload' INT HUP

# run the function
[ -z "$1" ] && help "$@"
$1 "$2"
