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

JOINPHP="${1:-/home/itahukamedia/public_html/studio.itahukamedia.com/public/join.php}"
TS="$(date +%Y%m%d_%H%M%S)"

if [ ! -f "$JOINPHP" ]; then
  echo "File not found: $JOINPHP"
  exit 1
fi

cp -a "$JOINPHP" "$JOINPHP.bak.$TS"
echo "Backup created: $JOINPHP.bak.$TS"

if grep -q 'async function enumerateDevices(' "$JOINPHP"; then
  echo "enumerateDevices() already exists. Nothing changed."
  exit 0
fi

TMP_HELPER="$(mktemp)"
TMP_OUT="$(mktemp)"

cat > "$TMP_HELPER" <<'EOF'
  async function enumerateDevices(){
    if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) return;
    const devices = await navigator.mediaDevices.enumerateDevices();

    const micId = (els.micSel && els.micSel.value) || load("lk_join_mic", "");
    const camId = (els.camSel && els.camSel.value) || load("lk_join_cam", "");

    const mics = devices.filter(d => d.kind === "audioinput");
    const cams = devices.filter(d => d.kind === "videoinput");

    if (els.micSel){
      els.micSel.innerHTML = `<option value="">Auto</option>` + mics.map(d => {
        const label = d.label || `Microphone (${d.deviceId.slice(0,6)}…)`;
        const sel = (d.deviceId === micId) ? "selected" : "";
        return `<option ${sel} value="${escapeHtml(d.deviceId)}">${escapeHtml(label)}</option>`;
      }).join("");
    }

    if (els.camSel){
      els.camSel.innerHTML = `<option value="">Auto</option>` + cams.map(d => {
        const label = d.label || `Camera (${d.deviceId.slice(0,6)}…)`;
        const sel = (d.deviceId === camId) ? "selected" : "";
        return `<option ${sel} value="${escapeHtml(d.deviceId)}">${escapeHtml(label)}</option>`;
      }).join("");
    }
  }

EOF

awk -v helper="$TMP_HELPER" '
BEGIN{
  inserted = 0
  while ((getline line < helper) > 0) block = block line "\n"
  close(helper)
}
{
  if (!inserted && $0 ~ /^  function cleanupTracks\(\)\{/){
    print
    getline
    print
    getline
    print
    getline
    print
    getline
    print
    getline
    print
    getline
    print
    printf "%s", block
    inserted = 1
    next
  }
  print
}
END{
  if (!inserted) printf "%s", block
}
' "$JOINPHP" > "$TMP_OUT"

mv "$TMP_OUT" "$JOINPHP"
rm -f "$TMP_HELPER"

echo
echo "Patch complete."
echo
echo "Run:"
echo "php -l \"$JOINPHP\""
echo "grep -n \"async function enumerateDevices\\|function cleanupTracks\" \"$JOINPHP\""
