#!/bin/bash
# Runs as the desktop user. No secrets, elevated shell, or persisted profiles.
# Parent stdin closes even on a crash; expiry is enforced independently of Dart.
set -u
export LC_ALL=C
uuid="${1:-}"
deadline="${2:-}"
[[ "$uuid" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ ]] || exit 2
[[ "$deadline" =~ ^[0-9]{1,16}$ ]] || exit 2
[[ -x /usr/bin/nmcli && -x /usr/bin/date ]] || exit 2
printf 'ready\n'
while true; do
  if read -r -t 1 command; then
    [[ "$command" == released ]] && exit 0
  else
    status=$?
    # A read timeout is >128; EOF means the parent closed or crashed.
    (( status <= 128 )) && break
  fi
  now="$(/usr/bin/date +%s%3N)"
  (( deadline > 0 && now >= deadline )) && break
done
# Retry for a pending Polkit/activation reply. The UUID belongs only to this
# connection attempt; never disconnect another network or another app instance.
until_time=$((SECONDS + 95))
while (( SECONDS < until_time )); do
  /usr/bin/nmcli --wait 5 connection down uuid "$uuid" </dev/null >/dev/null 2>&1 || true
  if /usr/bin/nmcli --wait 5 connection delete uuid "$uuid" </dev/null >/dev/null 2>&1; then
    exit 0
  fi
  sleep 1
done
exit 1
