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

cd ~/html
stamp="$(date +%y%m%d.%H%M%S)"
echo "==> Backup + patch ($stamp)"

# --------- Reissue G.php (scroll-friendly iframes) ----------
cp -a G.php "G.php.bak.$stamp" 2>/dev/null || true

cat > G.php <<'PHP'
<?php
// G.php — Full-screen stacked dashboard (scroll-friendly iframes)
date_default_timezone_set('America/New_York');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lupton Unified Dashboard</title>
<style>
html, body { margin:0; padding:0; width:100%; height:100%; }
body { background:#000; }
.panel { width:100vw; height:100vh; overflow:hidden; }
.panel iframe { width:100%; height:100%; border:0; overflow:auto; display:block; }
</style>
</head>
<body>

<div class="panel"><iframe src="/TBN.php"></iframe></div>
<div class="panel"><iframe src="/T227.php"></iframe></div>
<div class="panel"><iframe src="/t/g/index.php"></iframe></div>
<div class="panel"><iframe src="/t/a/index.php"></iframe></div>

<div class="panel"><iframe src="/3temps.graph.php"></iframe></div>
<div class="panel"><iframe src="/BME.graph.php"></iframe></div>
<div class="panel"><iframe src="/BME280.dewpoint.graph.php"></iframe></div>

<div class="panel"><iframe src="https://lupton.us/227flow.graph.php"></iframe></div>
<div class="panel"><iframe src="https://lupton.us/BNflow.graph.php"></iframe></div>

</body>
</html>
PHP

echo "    wrote: G.php (backup: G.php.bak.$stamp)"

# --------- Force LIGHT MODE inside flow pages ----------
for f in 227flow.graph.php BNflow.graph.php; do
  if [ ! -f "$f" ]; then
    echo "    WARN: missing $f (skipping)"
    continue
  fi

  cp -a "$f" "$f.bak.$stamp"
  echo "    backup: $f.bak.$stamp"

  # Add <meta name="color-scheme" content="light"> after <head> (only if not present)
  if grep -qi '<head' "$f" && ! grep -qi 'name="color-scheme"' "$f"; then
    perl -0777 -i -pe 's@(<head[^>]*>)@$1\n<meta name="color-scheme" content="light">@i' "$f"
  fi

  # Append FORCE_LIGHT_MODE block once
  if ! grep -q 'FORCE_LIGHT_MODE' "$f"; then
    cat >> "$f" <<'EOF'

<!-- FORCE_LIGHT_MODE -->
<style>
:root { color-scheme: light !important; }
html, body { background: #fff !important; color: #000 !important; }
table, thead, tbody, tr, th, td {
  background: #fff !important;
  color: #000 !important;
  border-color: #ddd !important;
}
</style>
<!-- /FORCE_LIGHT_MODE -->
EOF
  fi

  echo "    patched: $f"
done

echo "DONE."
echo "Safari: Shift-Reload. If still sticky: Develop menu -> Empty Caches."
