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

ROOT="${1:-/home/itahukamedia/public_html/studio.itahukamedia.com/public}"
JS="$ROOT/assets/js/modules/coproducer.inline-main.js"

if [ ! -f "$JS" ]; then
  echo "File not found: $JS" >&2
  exit 1
fi

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

# 1) VIDEO media block:
# Force preview muted, program audible.
perl -0pi -e '
s/v\.muted = false;/v.muted = !!isPreview;/g;
s/const hear = \(src\.type === "media"\) \? true : \(\(monitorMode === "preview"\) \? !!isPreview : !isPreview\);/const hear = !isPreview;/g;
s/v\.volume = hear \? Math\.max\(0, Math\.min\(1, Number\(ms\.vol \?\? 1\)\)\) : 0;/v.volume = isPreview ? 0 : Math.max(0, Math.min(1, Number(ms.vol ?? 1)));/g;
' "$JS"

# 2) AUDIO media block:
# Force preview muted, program audible.
perl -0pi -e '
s/a\.muted = false;/a.muted = !!isPreview;/g;
s/a\.volume = hear \? Math\.max\(0, Math\.min\(1, Number\(ms\.vol \?\? 1\)\)\) : 0;/a.volume = isPreview ? 0 : Math.max(0, Math.min(1, Number(ms.vol ?? 1)));/g;
' "$JS"

# 3) Keep studio return/master attach only on PROGRAM side.
# Replace any "if (hear) { attachMediaAudio(...); }" with program-only attach.
perl -0pi -e '
s/if \(hear\)\{\s*attachMediaAudio\(v, item\);\s*\}/if (!isPreview){ attachMediaAudio(v, item); }/g;
s/if \(hear\)\{\s*attachMediaAudio\(a, item\);\s*\}/if (!isPreview){ attachMediaAudio(a, item); }/g;
s/if \(!isPreview\)\s*\{\s*attachMediaAudio\(v, item\);\s*\}/if (!isPreview){ attachMediaAudio(v, item); }/g;
s/if \(!isPreview\)\s*\{\s*attachMediaAudio\(a, item\);\s*\}/if (!isPreview){ attachMediaAudio(a, item); }/g;
' "$JS"

chmod 0644 "$JS"

echo
echo "Patch applied."
echo
echo "Verify:"
grep -n 'v.muted = !!isPreview;' "$JS" || true
grep -n 'a.muted = !!isPreview;' "$JS" || true
grep -n 'const hear = !isPreview;' "$JS" || true
grep -n 'attachMediaAudio(v, item);' "$JS" || true
grep -n 'attachMediaAudio(a, item);' "$JS" || true
echo
echo "Then hard refresh coproducer.php and join.php"