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

if [ "$#" -lt 1 ]; then
  echo "Usage: $0 /path/to/studio/public"
  echo "Example: $0 /home/itahukamedia/public_html/studio.itahukamedia.com/public"
  exit 1
fi

ROOT="$1"
JOIN="$ROOT/join.php"

if [ ! -f "$JOIN" ]; then
  echo "Missing file: $JOIN" >&2
  exit 1
fi

if ! command -v php >/dev/null 2>&1; then
  echo "ERROR: php CLI not found in PATH." >&2
  exit 1
fi

STAMP="$(date +%Y%m%d_%H%M%S)"
cp -a "$JOIN" "$JOIN.bak.$STAMP"
echo "Backup created: $JOIN.bak.$STAMP"

php <<'PHP' "$JOIN"
<?php
$joinPath = $argv[1];

function fail($msg){ fwrite(STDERR, $msg . PHP_EOL); exit(1); }
function read_strict($p){ $c = file_get_contents($p); if ($c === false) fail("Cannot read: $p"); return $c; }
function write_strict($p, $c){ if (file_put_contents($p, $c) === false) fail("Cannot write: $p"); }
function patch_once(&$text, $search, $replace, $label){
  if (strpos($text, $replace) !== false) {
    echo "Already patched: $label\n";
    return;
  }
  $count = substr_count($text, $search);
  if ($count !== 1) fail("Patch failed for $label: expected 1 exact match, got $count");
  $text = str_replace($search, $replace, $text);
  echo "Patched: $label\n";
}

$join = read_strict($joinPath);

/* 1) Add cam+mic prompt helper before fetchToken() */
patch_once(
  $join,
  <<<'TXT'
  async function fetchToken({roomName, name, publish, subscribe}){
TXT,
  <<<'TXT'
  async function promptJoinDevices(){
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) return;
    const stream = await navigator.mediaDevices.getUserMedia({ audio:true, video:true });
    try{
      for (const t of (stream.getTracks() || [])){
        try{ t.stop(); }catch(_){}
      }
    }catch(_){}
  }

  async function fetchToken({roomName, name, publish, subscribe}){
TXT,
  'add promptJoinDevices helper'
);

/* 2) Prompt for both devices before fetchToken/connect */
patch_once(
  $join,
  <<<'TXT'
      const lkUrl = (els.lkurl && els.lkurl.value.trim()) || DEFAULT_LK_URL;
      const token = await fetchToken({ roomName, name, publish: true, subscribe: true });

      await lkRoom.connect(lkUrl, token);
TXT,
  <<<'TXT'
      const lkUrl = (els.lkurl && els.lkurl.value.trim()) || DEFAULT_LK_URL;

      // Prompt for BOTH camera + microphone before connecting
      await promptJoinDevices();

      const token = await fetchToken({ roomName, name, publish: true, subscribe: true });

      await lkRoom.connect(lkUrl, token);
TXT,
  'prompt devices before connect'
);

/* 3) Replace the "start OFF" block with auto-start full AV */
patch_once(
  $join,
  <<<'TXT'
      buildShare();
      refreshGuestStrip();

      // local screen stays "Not publishing" until MIC/CAM pressed
      detachLocal();
      if (localVU) localVU.setIdle();

      await enumerateDevices().catch(()=>{});
TXT,
  <<<'TXT'
      buildShare();
      refreshGuestStrip();

      // Start with BOTH camera and microphone ON automatically
      await ensureLocalCam();
      await ensureLocalMic();

      attachLocal();
      if (localVU && localAudio) localVU.attachTrack(localAudio);

      syncButtons();
      refreshGuestStrip();

      await enumerateDevices().catch(()=>{});
TXT,
  'auto-start both mic and cam'
);

write_strict($joinPath, $join);
echo "Done: $joinPath\n";
PHP

echo
echo "Patch complete."
echo
echo "Run syntax check:"
echo "php -l \"$JOIN\""
echo
echo "Then hard-refresh this page and test:"
echo "https://studio.itahukamedia.com/join.php?project=proj_0027932e57a24f63"
