#!/bin/bash
# GitHub sign-in through Android's browser on the bottom screen, with the one-time code typed in.
serial=${ADB_SERIAL:-127.0.0.1:5555}
adb connect "$serial" >/dev/null 2>&1
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
typed=
while IFS= read -r line <&"${GH[0]}"; do
  printf '%s\n' "$line"
  code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1)
  if [ -n "$code" ] && [ -z "$typed" ]; then
    typed=1
    echo >&"${GH[1]}"
    adb -s "$serial" shell "am start --display 2 -a android.intent.action.VIEW -d https://github.com/login/device" >/dev/null 2>&1
    # Chrome drops characters from `input text` and from fast key events on this page.
    keys=
    for ((i = 0; i < ${#code}; i++)); do
      c=${code:i:1}
      [ "$c" = - ] || keys+="input -d 2 keyevent KEYCODE_$c; sleep 0.4; "
    done
    (sleep 7; adb -s "$serial" shell "$keys" >/dev/null 2>&1) &
  fi
done
wait "$GH_PID"
