#!/usr/bin/env bash
set -u

PORT="${PORT:-5555}"
CONCURRENCY="${CONCURRENCY:-4}"

usage() {
  printf 'Usage: %s [--yes] <tv_ips.txt>\n' "$0"
  printf 'Dry-run is default. Add --yes to reboot TVs.\n'
}

YES=0
if [ "${1:-}" = "--yes" ]; then
  YES=1
  shift
fi

IP_FILE="${1:-}"
if [ -z "$IP_FILE" ]; then
  usage
  exit 2
fi

if [ ! -f "$IP_FILE" ]; then
  printf 'IP file not found: %s\n' "$IP_FILE" >&2
  exit 2
fi

if ! command -v adb >/dev/null 2>&1; then
  printf 'adb command not found. Install Android platform-tools first.\n' >&2
  exit 127
fi

reboot_one() {
  ip="$1"
  serial="$ip:$PORT"
  printf '[%s] connect %s\n' "$(date '+%F %T')" "$serial"
  adb connect "$serial" >/dev/null
  state="$(adb -s "$serial" get-state 2>&1 || true)"
  if [ "$state" != "device" ]; then
    printf '[%s] FAIL %s state=%s\n' "$(date '+%F %T')" "$ip" "$state"
    return 1
  fi
  if [ "$YES" -eq 1 ]; then
    adb -s "$serial" reboot
    printf '[%s] OK reboot sent %s\n' "$(date '+%F %T')" "$ip"
  else
    printf '[%s] DRY_RUN would reboot %s\n' "$(date '+%F %T')" "$ip"
  fi
}

active=0
while IFS= read -r line || [ -n "$line" ]; do
  ip="$(printf '%s' "$line" | sed 's/[[:space:]]//g')"
  [ -z "$ip" ] && continue
  case "$ip" in \#*) continue ;; esac
  reboot_one "$ip" &
  active=$((active + 1))
  if [ "$active" -ge "$CONCURRENCY" ]; then
    wait -n 2>/dev/null || wait
    active=$((active - 1))
  fi
done <"$IP_FILE"
wait
