#!/usr/bin/env bash

if command -v adb >/dev/null; then

# problem:
adb-tailscale-connect() {
  if ! command -v adb >/dev/null; then
    echo >&2 "'adb' not found in PATH!"
    return 1
  fi

  declare -a hostnames=()
  readarray -td $'\n' hostnames < <(
    tailscale status --json \
      | jq '.MagicDNSSuffix as $suffix | .Peer[].DNSName | rtrimstr(".") | rtrimstr("." + $suffix)' -r \
      | sort \
      | gum filter --height=12
  )
  if [[ "${#hostnames[@]}" -eq 0 ]]; then
    return 1
  fi

  (
    declare pids=()
    declare hostname
    for hostname in "${hostnames[@]}"; do
      (
        (set -x; tailscale ping "$hostname")
        declare port
        port=$(
          (set -x; nmap -p 30000-49999 "$hostname") \
            | grep -E '^[0-9]+/tcp open' | cut -d/ -f1
        )
        if [[ -n "$port" ]]; then
          echo "$hostname port=$port"
        fi
      ) &
      pids+=("$!")
    done
    trap : INT
    wait
    if [[ "$?" -eq 130 ]]; then # if interrupted
      (set -x; kill "${pids[@]}")
    fi
  )
}

fi
