#!/usr/bin/env bash
set -euo pipefail

CHECK_INTERVAL_SECONDS="${CHECK_INTERVAL_SECONDS:-2}"

print_usage() {
  cat <<'EOF'
Usage:
  ./power-adapter-stop-test.sh

Behavior:
  Watches incoming power/charging status and exits when power input is no longer present.
  This is a testing helper only; it does not shut down the machine.
EOF
}

log_msg() {
  local message="$1"
  printf '%s %s\n' "$(date -Is)" "${message}"
}

has_incoming_power() {
  local supply_path type_value online_value status_value

  shopt -s nullglob
  for supply_path in /sys/class/power_supply/*; do
    [[ -d "${supply_path}" ]] || continue
    [[ -r "${supply_path}/type" ]] || continue

    type_value=""
    read -r type_value < "${supply_path}/type" || type_value=""
    case "${type_value}" in
      Mains|USB|USB_C|USB_PD)
        if [[ -r "${supply_path}/online" ]]; then
          online_value="0"
          read -r online_value < "${supply_path}/online" || online_value="0"
          if [[ "${online_value}" == "1" ]]; then
            return 0
          fi
        fi
        ;;
    esac
  done

  for supply_path in /sys/class/power_supply/*; do
    [[ -d "${supply_path}" ]] || continue
    [[ -r "${supply_path}/type" ]] || continue

    type_value=""
    read -r type_value < "${supply_path}/type" || type_value=""
    if [[ "${type_value}" != "Battery" ]]; then
      continue
    fi

    if [[ -r "${supply_path}/status" ]]; then
      status_value="Unknown"
      read -r status_value < "${supply_path}/status" || status_value="Unknown"
      case "${status_value}" in
        Charging|Full)
          return 0
          ;;
      esac
    fi
  done

  return 1
}

watch_for_stop() {
  log_msg "Watching power/charging status (poll every ${CHECK_INTERVAL_SECONDS}s)."
  log_msg "Leave this script running, then unplug adapter to test detection."

  if ! has_incoming_power; then
    log_msg "Input power already absent (not charging)."
    exit 0
  fi

  log_msg "Input power currently present."

  while true; do
    if ! has_incoming_power; then
      log_msg "Detected stop: adapter/incoming power is no longer present."
      exit 0
    fi
    sleep "${CHECK_INTERVAL_SECONDS}"
  done
}

main() {
  case "${1:-}" in
    --help|-h)
      print_usage
      ;;
    "")
      watch_for_stop
      ;;
    *)
      print_usage
      exit 1
      ;;
  esac
}

main "${@}"
