#!/usr/bin/env bash
# Puts your Dispatch app HTML on the server as a PWA with login + share/export menu.
# Usage:  sudo bash scripts/add-app.sh /path/to/your-dispatch.html
set -euo pipefail
SRC="${1:-}"
APP_DIR="${APP_DIR:-/opt/bkry-dispatch}"
WEB_ROOT="$APP_DIR/public"
[ -f "$SRC" ] || { echo "Give the path to your app HTML file, e.g. sudo bash scripts/add-app.sh dispatch.html"; exit 1; }
[ -d "$WEB_ROOT" ] || { echo "$WEB_ROOT not found. Run scripts/deploy.sh first."; exit 1; }

[ -f "$WEB_ROOT/index.html" ] && cp "$WEB_ROOT/index.html" "$WEB_ROOT/index.prev.html"

python3 - "$SRC" "$WEB_ROOT/index.html" <<'PY'
import re, sys
src, dst = sys.argv[1], sys.argv[2]
html = open(src, encoding='utf-8').read()
block = """<!-- BKRY-PWA:START -->
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#9E4130">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Dispatch">
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/icons/favicon-32.png">
<script src="/pwa.js" defer></script>
<script src="/bkry-tools.js" defer></script>
<!-- BKRY-PWA:END -->"""
html = re.sub(r'<!-- BKRY-PWA:START -->.*?<!-- BKRY-PWA:END -->\s*', '', html, flags=re.S)
if not re.search(r'name=["\']viewport', html, re.I):
    block = '<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">\n' + block
if re.search(r'</head>', html, re.I):
    html = re.sub(r'</head>', lambda m: block + '\n</head>', html, count=1, flags=re.I)
elif re.search(r'<body', html, re.I):
    html = re.sub(r'(<body)', lambda m: '<head>' + block + '</head>\n' + m.group(1), html, count=1, flags=re.I)
else:
    html = '<!DOCTYPE html><html><head><meta charset="utf-8">' + block + '</head><body>' + html + '</body></html>'
open(dst, 'w', encoding='utf-8').write(html)
print('App installed to', dst)
PY

STAMP=$(date +%Y%m%d%H%M%S)
sed -i "s/^const VERSION = .*/const VERSION = 'bkry-dispatch-$STAMP';/" "$WEB_ROOT/sw.js"
chown -R bkry:bkry "$APP_DIR" 2>/dev/null || true
echo "Done. Refresh the site — installed phones will show an 'Update' banner."
echo "Previous version saved as $WEB_ROOT/index.prev.html"
