#!/usr/bin/env bash
# ACERO REALTIME DB v47
# A Firebase-style real-time database for your own VPS: REST API, live updates (SSE),
# rules per website, API keys, and a mobile web panel. By Jerald Acero.
#
# Usage (as root, Debian / Ubuntu):
#   bash install.sh                       # HTTPS on your VPS IP (Let's Encrypt IP certificate)
#   bash install.sh db.yourdomain.com     # HTTPS on your domain (point its A record to this VPS first)
#   bash install.sh db.yourdomain.com MyPassword12     # also choose the panel password (8+ chars)
#   bash install.sh --remove-old          # first remove an old ACERO SCRIPT (V2Ray panel) from this VPS
#
# Already installed? Run it again: it upgrades the program and KEEPS your data, password and secret path.
# Reset the panel password later:   acero-rtdb setpw 'newpassword'
# Backup / restore:                 acero-rtdb backup      |     acero-rtdb restore FILE.tar.gz
#
# Open ports 80/tcp and 443/tcp in your VPS provider firewall (80 is needed for the certificate).

set -euo pipefail

TEST="${ACERO_TEST:-0}"
if [[ "$TEST" == "1" ]]; then
  APP="${ACERO_TEST_DIR:?set ACERO_TEST_DIR}/app"
else
  APP=/opt/acero-rtdb
fi
DATA=${APP}/data
CERT_DIR=${APP}/cert
ACME_HOME=${APP}/acme
API_PORT=8087
PANEL_PORT=8088
SVC_USER=acerodb
INFO=/root/acero-rtdb-info.txt
[[ "$TEST" == "1" ]] && INFO="${ACERO_TEST_DIR}/info.txt"

REMOVE_OLD=0
if [[ "${1:-}" == "--remove-old" ]]; then REMOVE_OLD=1; shift; fi
DOMAIN="${1:-}"
PANEL_PW="${2:-$(head -c 24 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c 14)}"

if [[ "$TEST" != "1" && $EUID -ne 0 ]]; then
  echo "Run as root (sudo -i)." >&2
  exit 1
fi
if [[ -n "$DOMAIN" ]]; then
  if [[ "$DOMAIN" =~ ^[0-9.]+$ || ! "$DOMAIN" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?\.[A-Za-z]{2,}$ ]]; then
    echo "\"$DOMAIN\" does not look like a domain name (example: db.yourdomain.com). Leave it out to use the VPS IP." >&2
    exit 1
  fi
fi
if [[ ${#PANEL_PW} -lt 8 ]]; then
  echo "The panel password needs at least 8 characters." >&2
  exit 1
fi

# ---------------------------------------------------------------- old ACERO SCRIPT (V2Ray panel)
old_found() { [[ -d /opt/v2panel ]] || { command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files 2>/dev/null | grep -q '^v2panel.service'; }; }

if [[ "$TEST" != "1" ]] && old_found; then
  if [[ $REMOVE_OLD -ne 1 ]]; then
    cat >&2 <<'OLDMSG'
This VPS already runs the OLD ACERO SCRIPT (V2Ray / SSH panel).
ACERO REALTIME DB needs ports 80 and 443, which that script uses.

Best: use a fresh VPS. Or remove the old script first. This DELETES its users and VPN setup
(a backup is saved in /root first):

    bash install.sh --remove-old
OLDMSG
    exit 1
  fi
  echo "Removing the old ACERO SCRIPT. A backup goes to /root first. Press Ctrl+C within 8 seconds to cancel."
  sleep 8
  BK=/root/v2panel-backup-$(date +%Y%m%d-%H%M).tar.gz
  tar czf "$BK" /opt/v2panel 2>/dev/null || true
  echo "Backup saved: $BK"
  for u in v2panel v2sshws acero-slowdns acero-sslmux acero-ovpn-ssl acero-ovpn-tcp acero-ovpn-udp acero-ovpn-fw acero-ovpn-nat \
           acero-dns acero-tunnel acero-turbo acero-cert-renew.timer acero-cert-renew v2ray stunnel4; do
    systemctl disable --now "$u" >/dev/null 2>&1 || true
  done
  for f in /etc/systemd/system/v2panel.service /etc/systemd/system/v2sshws.service /etc/systemd/system/acero-*.service \
           /etc/systemd/system/acero-*.timer /etc/systemd/system/v2ray.service.d; do
    rm -rf $f
  done
  rm -f /etc/nginx/conf.d/v2ray-ws.conf /etc/nginx/acero-v2ban.conf
  rm -rf /opt/v2panel
  systemctl daemon-reload || true
  echo "Old ACERO SCRIPT removed. (Packages like v2ray and openvpn stay installed but are not running.)"
fi

# ---------------------------------------------------------------- 1. dependencies
echo "[1/7] Installing dependencies..."
if [[ "$TEST" != "1" ]]; then
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -y
  apt-get install -y curl nginx python3 ca-certificates openssl
fi
command -v python3 >/dev/null || { echo "python3 is missing." >&2; exit 1; }
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' || { echo "Python 3.8 or newer is required." >&2; exit 1; }
python3 -c 'import sqlite3' || { echo "Python sqlite3 module is missing (apt-get install python3)." >&2; exit 1; }

UPGRADE=0
if [[ -f ${DATA}/config.json && -f ${DATA}/rtdb.sqlite3 ]]; then
  UPGRADE=1
  echo "Existing install found: upgrading (keeping your data, password and secret path)."
fi

# Ports 80/443 must be free, or used by nginx already.
if [[ "$TEST" != "1" && "${ACERO_FORCE:-0}" != "1" ]] && command -v ss >/dev/null 2>&1; then
  BUSY="$(ss -ltnpH '( sport = :80 or sport = :443 )' 2>/dev/null | grep -v '"nginx"' || true)"
  if [[ -n "$BUSY" ]]; then
    echo "Port 80 or 443 is used by another program:" >&2
    echo "$BUSY" >&2
    echo "Stop it first (or use a fresh VPS). To install anyway: ACERO_FORCE=1 bash install.sh ..." >&2
    exit 1
  fi
fi

# ---------------------------------------------------------------- 2. program files
echo "[2/7] Writing program files..."
mkdir -p ${DATA} ${CERT_DIR} ${ACME_HOME}

cat > ${APP}/rtdb.py <<'ACERO_RTDB_PY_EOF'
#!/usr/bin/env python3
"""ACERO REALTIME DB engine (stdlib only, Python 3.8+).

Firebase-like JSON tree database:
  * REST API   : /<site>/<path>.json  (GET PUT POST PATCH DELETE) + ?key=API_KEY
  * Realtime   : same URL with  Accept: text/event-stream  (Server-Sent Events)
  * Rules      : Firebase-style .read / .write / .validate per website
  * Site users : /_auth/<site>/signup|login  -> token for  ?auth=TOKEN  (rules see `auth`)
"""
import os, sys, re, ast, copy, json, time, hmac, base64, queue, secrets, sqlite3, hashlib, fnmatch, threading, argparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs, unquote

VERSION = 'v47'
MAX_BODY = 4 * 1024 * 1024
MAX_RULES = 100 * 1024
MAX_STREAMS = 800
TOKEN_TTL = 7 * 24 * 3600
SITE_RE = re.compile(r'^[a-z0-9]([a-z0-9-]{0,38}[a-z0-9])?$')
RESERVED = {'health', 'sdk', 'panel', 'admin', 'api', 'static'}
BAD_KEY = re.compile(r'[.$#\[\]/\x00-\x1f\x7f]')
DEFAULT_RULES = {"rules": {".read": False, ".write": False}}


def now_ms():
    return int(time.time() * 1000)


def b64u(b):
    return base64.urlsafe_b64encode(b).rstrip(b'=').decode()


def b64d(s):
    return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))


class ApiError(Exception):
    def __init__(self, code, msg):
        Exception.__init__(self, msg)
        self.code, self.msg = code, msg


# ------------------------------------------------------------------ data helpers
def valid_key(k):
    return isinstance(k, str) and 0 < len(k) <= 768 and not BAD_KEY.search(k)


def clean(v, depth=0):
    """Normalize incoming JSON: lists -> objects, empty -> None, validate keys."""
    if depth > 32:
        raise ApiError(400, 'Data is nested too deeply')
    if v is None:
        return None
    if isinstance(v, bool):
        return v
    if isinstance(v, (int, float)):
        if isinstance(v, float) and (v != v or v in (float('inf'), float('-inf'))):
            raise ApiError(400, 'Invalid number')
        return v
    if isinstance(v, str):
        return v
    if isinstance(v, list):
        v = dict((str(i), x) for i, x in enumerate(v))
    if isinstance(v, dict):
        out = {}
        for k, x in v.items():
            if not valid_key(k):
                raise ApiError(400, 'Invalid key: ' + repr(k)[:40])
            c = clean(x, depth + 1)
            if c is not None:
                out[k] = c
        return out or None
    raise ApiError(400, 'Unsupported value')


def leaves(v, prefix):
    if isinstance(v, dict):
        for k, x in v.items():
            for r in leaves(x, prefix + '/' + k):
                yield r
    else:
        if prefix == '':
            raise ApiError(400, 'The database root must be an object')
        yield prefix, json.dumps(v, ensure_ascii=False)


def get_in(tree, rel):
    for s in rel:
        if isinstance(tree, dict) and s in tree:
            tree = tree[s]
        else:
            return None
    return tree


def prune(t):
    if isinstance(t, dict):
        for k in list(t):
            t[k] = prune(t[k])
            if t[k] is None:
                del t[k]
        return t or None
    return t


def set_in(base, rel, V):
    if not rel:
        return V
    if not isinstance(base, dict):
        base = {}
    d = base
    for s in rel[:-1]:
        nxt = d.get(s)
        if not isinstance(nxt, dict):
            nxt = {}
            d[s] = nxt
        d = nxt
    if V is None:
        d.pop(rel[-1], None)
    else:
        d[rel[-1]] = V
    return prune(base)


_ALPHA = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
_push = {'t': 0, 'r': [0] * 12}
_push_lock = threading.Lock()


def push_id():
    """Firebase-style 20 char, time-ordered key."""
    with _push_lock:
        now = now_ms()
        dup = now == _push['t']
        _push['t'] = now
        t, n = [], now
        for _ in range(8):
            t.append(_ALPHA[n % 64])
            n //= 64
        if not dup:
            _push['r'] = [secrets.randbelow(64) for _ in range(12)]
        else:
            r = _push['r']
            i = 11
            while i >= 0 and r[i] == 63:
                r[i] = 0
                i -= 1
            if i >= 0:
                r[i] += 1
        return ''.join(reversed(t)) + ''.join(_ALPHA[x] for x in _push['r'])


def spath(segs):
    return '/' + '/'.join(segs) if segs else ''


# ------------------------------------------------------------------ store
class Store:
    def __init__(self, base):
        os.makedirs(base, exist_ok=True)
        self.base = base
        self.lock = threading.RLock()
        self.db = sqlite3.connect(os.path.join(base, 'rtdb.sqlite3'), check_same_thread=False, isolation_level=None)
        self.db.execute('PRAGMA journal_mode=WAL')
        self.db.execute('PRAGMA synchronous=NORMAL')
        self.db.executescript('''
        CREATE TABLE IF NOT EXISTS sites(id TEXT PRIMARY KEY, name TEXT, public_key TEXT UNIQUE,
            secret_key TEXT UNIQUE, origins TEXT DEFAULT '', rules TEXT, created INTEGER, enabled INTEGER DEFAULT 1);
        CREATE TABLE IF NOT EXISTS nodes(site TEXT, path TEXT, val TEXT, PRIMARY KEY(site, path)) WITHOUT ROWID;
        CREATE TABLE IF NOT EXISTS users(site TEXT, uid TEXT, email TEXT, salt TEXT, pw TEXT, created INTEGER,
            PRIMARY KEY(site, uid));
        CREATE UNIQUE INDEX IF NOT EXISTS users_email ON users(site, email);
        CREATE TABLE IF NOT EXISTS usage(site TEXT, day TEXT, reads INTEGER DEFAULT 0, writes INTEGER DEFAULT 0,
            bytes_out INTEGER DEFAULT 0, PRIMARY KEY(site, day)) WITHOUT ROWID;
        ''')
        self.listeners = []
        self._site_cache = {}
        self._usage = {}
        kf = os.path.join(base, 'secret.key')
        if not os.path.exists(kf):
            with open(kf, 'w') as f:
                f.write(secrets.token_hex(32))
            os.chmod(kf, 0o600)
        self.secret = open(kf).read().strip().encode()
        t = threading.Thread(target=self._flush_loop, daemon=True)
        t.start()

    # ---- usage counters (flushed every 30 s)
    def bump(self, site, kind, nbytes=0):
        with self.lock:
            u = self._usage.setdefault(site, [0, 0, 0])
            if kind == 'r':
                u[0] += 1
                u[2] += nbytes
            else:
                u[1] += 1

    def flush_usage(self):
        with self.lock:
            data, self._usage = self._usage, {}
            day = time.strftime('%Y-%m-%d', time.gmtime())
            for site, (r, w, b) in data.items():
                self.db.execute('INSERT INTO usage(site,day,reads,writes,bytes_out) VALUES(?,?,?,?,?) '
                                'ON CONFLICT(site,day) DO UPDATE SET reads=reads+?, writes=writes+?, bytes_out=bytes_out+?',
                                (site, day, r, w, b, r, w, b))

    def _flush_loop(self):
        while True:
            time.sleep(30)
            try:
                self.flush_usage()
            except Exception:
                pass

    # ---- data
    def get(self, site, path):
        with self.lock:
            rows = self.db.execute('SELECT path,val FROM nodes WHERE site=? AND (path=? OR (path>=? AND path<?))',
                                   (site, path, path + '/', path + '0')).fetchall()
        root = None
        for p, v in rows:
            val = json.loads(v)
            if p == path:
                return val
            rel = p[len(path) + 1:].split('/')
            if root is None:
                root = {}
            d = root
            for s in rel[:-1]:
                d = d.setdefault(s, {})
            d[rel[-1]] = val
        return root

    def _set(self, site, path, value):
        self.db.execute('DELETE FROM nodes WHERE site=? AND (path=? OR (path>=? AND path<?))',
                        (site, path, path + '/', path + '0'))
        parts = path.split('/')[1:] if path else []
        for i in range(1, len(parts)):
            self.db.execute('DELETE FROM nodes WHERE site=? AND path=?', (site, '/' + '/'.join(parts[:i])))
        if value is not None:
            self.db.executemany('INSERT OR REPLACE INTO nodes(site,path,val) VALUES(?,?,?)',
                                [(site, p, v) for p, v in leaves(value, path)])

    def write(self, site, ops):
        """ops = [(path, cleaned_value)] applied in ONE transaction, then listeners are told."""
        with self.lock:
            self.db.execute('BEGIN')
            try:
                for path, value in ops:
                    self._set(site, path, value)
                self.db.execute('COMMIT')
            except Exception:
                self.db.execute('ROLLBACK')
                raise
        self.bump(site, 'w')
        for cb in list(self.listeners):
            cb(site, [p for p, _ in ops])

    # ---- sites
    def site(self, sid):
        if not sid:
            return None
        r = self._site_cache.get(sid)
        if r and time.time() - r[0] < 5:
            return r[1]
        with self.lock:
            row = self.db.execute('SELECT id,name,public_key,secret_key,origins,rules,created,enabled FROM sites WHERE id=?',
                                  (sid,)).fetchone()
        d = None
        if row:
            d = dict(zip(('id', 'name', 'public_key', 'secret_key', 'origins', 'rules', 'created', 'enabled'), row))
            try:
                d['rules_obj'] = json.loads(d['rules'])
            except Exception:
                d['rules_obj'] = DEFAULT_RULES
        self._site_cache[sid] = (time.time(), d)
        return d

    def sites(self):
        with self.lock:
            ids = [r[0] for r in self.db.execute('SELECT id FROM sites ORDER BY created').fetchall()]
        return [self.site(i) for i in ids]

    def create_site(self, sid, name='', origins=''):
        if not SITE_RE.match(sid or '') or sid in RESERVED:
            raise ApiError(400, 'Site id: 1-40 chars, a-z 0-9 and "-" only (not a reserved word)')
        if self.site(sid):
            raise ApiError(409, 'Site already exists')
        pk, sk = 'acero_pk_' + secrets.token_urlsafe(18), 'acero_sk_' + secrets.token_urlsafe(24)
        with self.lock:
            self.db.execute('INSERT INTO sites(id,name,public_key,secret_key,origins,rules,created) VALUES(?,?,?,?,?,?,?)',
                            (sid, name or sid, pk, sk, origins, json.dumps(DEFAULT_RULES, indent=2), now_ms()))
        self._site_cache.pop(sid, None)
        return self.site(sid)

    def update_site(self, sid, **kw):
        allowed = {'name', 'origins', 'enabled'}
        with self.lock:
            for k, v in kw.items():
                if k in allowed:
                    self.db.execute('UPDATE sites SET %s=? WHERE id=?' % k, (v, sid))
        self._site_cache.pop(sid, None)

    def rotate_key(self, sid, which):
        col = 'public_key' if which == 'public' else 'secret_key'
        new = ('acero_pk_' + secrets.token_urlsafe(18)) if which == 'public' else ('acero_sk_' + secrets.token_urlsafe(24))
        with self.lock:
            self.db.execute('UPDATE sites SET %s=? WHERE id=?' % col, (new, sid))
        self._site_cache.pop(sid, None)
        return new

    def set_rules(self, sid, text):
        if len(text) > MAX_RULES:
            raise ApiError(400, 'Rules are too large')
        try:
            obj = json.loads(text)
        except ValueError as e:
            raise ApiError(400, 'Rules are not valid JSON: %s' % e)
        errs = check_rules(obj)
        if errs:
            raise ApiError(400, 'Rules error: ' + '; '.join(errs[:5]))
        with self.lock:
            self.db.execute('UPDATE sites SET rules=? WHERE id=?', (json.dumps(obj, indent=2, ensure_ascii=False), sid))
        self._site_cache.pop(sid, None)

    def delete_site(self, sid):
        with self.lock:
            for t in ('nodes', 'users', 'usage'):
                self.db.execute('DELETE FROM %s WHERE site=?' % t, (sid,))
            self.db.execute('DELETE FROM sites WHERE id=?', (sid,))
        self._site_cache.pop(sid, None)

    def site_stats(self, sid):
        with self.lock:
            n, size = self.db.execute('SELECT count(*), coalesce(sum(length(path)+length(val)),0) FROM nodes WHERE site=?', (sid,)).fetchone()
            users = self.db.execute('SELECT count(*) FROM users WHERE site=?', (sid,)).fetchone()[0]
            use = self.db.execute('SELECT day,reads,writes,bytes_out FROM usage WHERE site=? ORDER BY day DESC LIMIT 14', (sid,)).fetchall()
        return {'nodes': n, 'bytes': size, 'users': users, 'usage': use}

    # ---- site users + tokens
    def _hash(self, pw, salt):
        return hashlib.pbkdf2_hmac('sha256', pw.encode(), salt, 150000).hex()

    def signup(self, site, email, pw):
        email = (email or '').strip().lower()
        if not re.match(r'^[^@\s]+@[^@\s]+\.[^@\s]+$', email) or len(email) > 200:
            raise ApiError(400, 'Invalid email')
        if not isinstance(pw, str) or len(pw) < 6 or len(pw) > 200:
            raise ApiError(400, 'Password must be 6-200 characters')
        salt = secrets.token_bytes(16)
        uid = secrets.token_hex(10)
        try:
            with self.lock:
                self.db.execute('INSERT INTO users(site,uid,email,salt,pw,created) VALUES(?,?,?,?,?,?)',
                                (site, uid, email, salt.hex(), self._hash(pw, salt), now_ms()))
        except sqlite3.IntegrityError:
            raise ApiError(409, 'Email already registered')
        return uid, email

    def login(self, site, email, pw):
        email = (email or '').strip().lower()
        with self.lock:
            row = self.db.execute('SELECT uid,salt,pw FROM users WHERE site=? AND email=?', (site, email)).fetchone()
        salt = bytes.fromhex(row[1]) if row else b'x' * 16
        h = self._hash(pw if isinstance(pw, str) else '', salt)
        if not row or not hmac.compare_digest(h, row[2]):
            raise ApiError(401, 'Wrong email or password')
        return row[0], email

    def users(self, site):
        with self.lock:
            return self.db.execute('SELECT uid,email,created FROM users WHERE site=? ORDER BY created DESC LIMIT 500', (site,)).fetchall()

    def delete_user(self, site, uid):
        with self.lock:
            self.db.execute('DELETE FROM users WHERE site=? AND uid=?', (site, uid))

    def make_token(self, site, uid, email):
        body = b64u(json.dumps({'s': site, 'u': uid, 'm': email, 'e': int(time.time()) + TOKEN_TTL}).encode())
        sig = b64u(hmac.new(self.secret, body.encode(), hashlib.sha256).digest())
        return body + '.' + sig

    def check_token(self, site, tok):
        try:
            body, sig = tok.split('.')
            good = b64u(hmac.new(self.secret, body.encode(), hashlib.sha256).digest())
            if not hmac.compare_digest(good, sig):
                return None
            d = json.loads(b64d(body))
            if d['s'] != site or d['e'] < time.time():
                return None
            return {'uid': d['u'], 'email': d['m']}
        except Exception:
            return None


# ------------------------------------------------------------------ realtime hub
def related(a, b):
    return a == b or a == '' or b == '' or a.startswith(b + '/') or b.startswith(a + '/')


class Sub:
    def __init__(self, site, path):
        self.site, self.path = site, path
        self.q = queue.Queue(maxsize=1)

    def tick(self):
        try:
            self.q.put_nowait(1)
        except queue.Full:
            pass


class Hub:
    def __init__(self, store):
        self.lock = threading.Lock()
        self.subs = {}
        store.listeners.append(self.notify)

    def subscribe(self, site, path):
        s = Sub(site, path)
        with self.lock:
            self.subs.setdefault(site, set()).add(s)
        return s

    def unsubscribe(self, s):
        with self.lock:
            self.subs.get(s.site, set()).discard(s)

    def count(self):
        with self.lock:
            return sum(len(v) for v in self.subs.values())

    def notify(self, site, paths):
        with self.lock:
            subs = list(self.subs.get(site, ()))
        for s in subs:
            if any(related(s.path, p) for p in paths):
                s.tick()


# ------------------------------------------------------------------ rules language (Firebase-like subset)
class S(str):
    def contains(self, x):
        return str(x) in self

    def beginsWith(self, x):
        return self.startswith(str(x))

    def endsWith(self, x):
        return self.endswith(str(x))

    def matches(self, rx):
        if not isinstance(rx, str) or len(self) > 5000 or len(rx) > 300:
            return False
        return re.search(rx, self) is not None

    def toLowerCase(self):
        return S(self.lower())

    def toUpperCase(self):
        return S(self.upper())


def wrap(v):
    return S(v) if isinstance(v, str) and not isinstance(v, S) else v


class AuthObj(object):
    def __init__(self, d):
        self.d = d


class Ctx(object):
    def __init__(self, store, site, auth, write=None):
        self.store, self.site, self.auth, self.write = store, site, auth, write
        self.cache = {}
        self.now = now_ms()

    def old(self, segs):
        k = tuple(segs)
        if k not in self.cache:
            self.cache[k] = self.store.get(self.site, spath(segs))
        return self.cache[k]

    def value_at(self, segs, new):
        if not new or self.write is None:
            return self.old(segs)
        w, V = self.write
        n, m = len(segs), len(w)
        if n >= m and segs[:m] == w:
            return get_in(V, segs[m:])
        if n < m and w[:n] == segs:
            return set_in(copy.deepcopy(self.old(segs)), w[n:], V)
        return self.old(segs)


class Snap(object):
    def __init__(self, ctx, segs, new):
        self.ctx, self.segs, self.new = ctx, list(segs), new

    def _v(self):
        return self.ctx.value_at(self.segs, self.new)

    def val(self):
        v = self._v()
        return wrap(v)

    def exists(self):
        return self._v() is not None

    def child(self, p):
        extra = [x for x in str(p).split('/') if x]
        return Snap(self.ctx, self.segs + extra, self.new)

    def parent(self):
        return Snap(self.ctx, self.segs[:-1], self.new)

    def hasChild(self, p):
        return self.child(p).exists()

    def hasChildren(self, names=None):
        v = self._v()
        if not isinstance(v, dict) or not v:
            return False
        return all(n in v for n in names) if names is not None else True

    def numChildren(self):
        v = self._v()
        return len(v) if isinstance(v, dict) else 0

    def isString(self):
        return isinstance(self._v(), str)

    def isNumber(self):
        v = self._v()
        return isinstance(v, (int, float)) and not isinstance(v, bool)

    def isBoolean(self):
        return isinstance(self._v(), bool)


SNAP_METHODS = {'val', 'exists', 'child', 'parent', 'hasChild', 'hasChildren', 'numChildren', 'isString', 'isNumber', 'isBoolean'}
STR_METHODS = {'contains', 'beginsWith', 'endsWith', 'matches', 'toLowerCase', 'toUpperCase'}
NAMES = {'auth', 'now', 'root', 'data', 'newData'}
_STRLIT = re.compile(r"""('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")""")


def translate(expr):
    parts = _STRLIT.split(expr)
    for i in range(0, len(parts), 2):
        s = parts[i].replace('===', '==').replace('!==', '!=').replace('&&', ' and ').replace('||', ' or ')
        s = re.sub(r'!(?!=)', ' not ', s)
        s = re.sub(r'\bnull\b', 'None', s)
        s = re.sub(r'\btrue\b', 'True', s)
        s = re.sub(r'\bfalse\b', 'False', s)
        s = re.sub(r'\$([A-Za-z_]\w*)', r'_v_\1', s)
        parts[i] = s
    return ''.join(parts)


OK_BIN = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod)
OK_CMP = (ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE)


def _check(n):
    t = type(n)
    if t is ast.Expression:
        return _check(n.body)
    if t is ast.BoolOp:
        return [_check(v) for v in n.values]
    if t is ast.UnaryOp:
        if not isinstance(n.op, (ast.Not, ast.USub)):
            raise ValueError('operator not allowed')
        return _check(n.operand)
    if t is ast.BinOp:
        if not isinstance(n.op, OK_BIN):
            raise ValueError('operator not allowed')
        _check(n.left)
        return _check(n.right)
    if t is ast.Compare:
        if len(n.ops) != 1 or not isinstance(n.ops[0], OK_CMP):
            raise ValueError('comparison not allowed')
        _check(n.left)
        return _check(n.comparators[0])
    if t is ast.Constant:
        if not (n.value is None or isinstance(n.value, (str, int, float, bool))):
            raise ValueError('constant not allowed')
        return
    if t is ast.Name:
        if not (n.id in NAMES or n.id.startswith('_v_')):
            raise ValueError('unknown name: ' + n.id)
        return
    if t is ast.Attribute:
        if n.attr.startswith('_'):
            raise ValueError('attribute not allowed')
        return _check(n.value)
    if t is ast.Call:
        if n.keywords or not isinstance(n.func, ast.Attribute):
            raise ValueError('call not allowed')
        _check(n.func)
        return [_check(a) for a in n.args]
    if t is ast.List:
        return [_check(e) for e in n.elts]
    raise ValueError('syntax not allowed: ' + t.__name__)


_cache = {}


def compile_expr(expr):
    t = _cache.get(expr)
    if t is None:
        if len(expr) > 600:
            raise ValueError('expression too long')
        t = ast.parse(translate(expr).strip(), mode='eval')
        _check(t)
        if len(_cache) > 2000:
            _cache.clear()
        _cache[expr] = t
    return t


def ev(n, env):
    t = type(n)
    if t is ast.Expression:
        return ev(n.body, env)
    if t is ast.Constant:
        return wrap(n.value)
    if t is ast.Name:
        return env[n.id]
    if t is ast.List:
        return [ev(e, env) for e in n.elts]
    if t is ast.BoolOp:
        is_and = isinstance(n.op, ast.And)
        r = None
        for v in n.values:
            r = ev(v, env)
            if is_and and not r:
                return r
            if not is_and and r:
                return r
        return r
    if t is ast.UnaryOp:
        v = ev(n.operand, env)
        return (not v) if isinstance(n.op, ast.Not) else -v
    if t is ast.BinOp:
        a, b = ev(n.left, env), ev(n.right, env)
        if isinstance(n.op, ast.Add):
            if isinstance(a, str) or isinstance(b, str):
                return S(str(a) + str(b))
            return a + b
        if isinstance(n.op, ast.Sub):
            return a - b
        if isinstance(n.op, ast.Mult):
            return a * b
        if isinstance(n.op, ast.Div):
            return a / b
        return a % b
    if t is ast.Compare:
        a, b, op = ev(n.left, env), ev(n.comparators[0], env), n.ops[0]
        if isinstance(op, ast.Eq):
            return a == b
        if isinstance(op, ast.NotEq):
            return a != b
        try:
            if isinstance(a, bool) or isinstance(b, bool) or a is None or b is None:
                return False
            if isinstance(a, str) != isinstance(b, str):
                return False
            return {ast.Lt: a < b, ast.LtE: a <= b, ast.Gt: a > b, ast.GtE: a >= b}[type(op)]
        except TypeError:
            return False
    if t is ast.Attribute:
        o = ev(n.value, env)
        name = n.attr
        if isinstance(o, Snap) and name in SNAP_METHODS:
            return getattr(o, name)
        if isinstance(o, S):
            if name == 'length':
                return len(o)
            if name in STR_METHODS:
                return getattr(o, name)
        if isinstance(o, AuthObj):
            return wrap(o.d.get(name))
        raise ValueError('bad attribute')
    if t is ast.Call:
        f = ev(n.func, env)
        return f(*[ev(a, env) for a in n.args])
    raise ValueError('bad syntax')


def eval_rule(expr, env):
    if expr is True or expr is False:
        return expr
    if not isinstance(expr, str):
        return False
    try:
        return bool(ev(compile_expr(expr), env))
    except Exception:
        return False


def check_rules(obj, path='rules'):
    """Static check of a rules document. Returns a list of error strings."""
    errs = []
    if path == 'rules':
        if not isinstance(obj, dict) or not isinstance(obj.get('rules'), dict):
            return ['top level must be {"rules": {...}}']
        obj = obj['rules']

    def walk(node, p):
        if not isinstance(node, dict):
            errs.append('%s must be an object' % p)
            return
        for k, v in node.items():
            if k in ('.read', '.write', '.validate'):
                if isinstance(v, bool):
                    continue
                if not isinstance(v, str):
                    errs.append('%s/%s must be true, false or a string' % (p, k))
                    continue
                try:
                    compile_expr(v)
                except Exception as e:
                    errs.append('%s/%s: %s' % (p, k, str(e)[:80]))
            elif k.startswith('.'):
                continue
            elif k.startswith('$'):
                if not re.match(r'^\$[A-Za-z_]\w*$', k):
                    errs.append('%s: bad wildcard %s' % (p, k))
                walk(v, p + '/' + k)
            else:
                if not valid_key(k):
                    errs.append('%s: bad key %s' % (p, k[:30]))
                    continue
                walk(v, p + '/' + k)
    walk(obj, path)
    return errs


def rule_child(node, seg):
    if not isinstance(node, dict):
        return None, None
    if seg in node:
        return node[seg], None
    for k, v in node.items():
        if k.startswith('$'):
            return v, k
    return None, None


def make_env(ctx, segs, vars_):
    env = {'auth': AuthObj(ctx.auth) if ctx.auth else None, 'now': ctx.now,
           'root': Snap(ctx, [], False), 'data': Snap(ctx, segs, False), 'newData': Snap(ctx, segs, True)}
    for k, v in vars_.items():
        env['_v_' + k[1:]] = S(v)
    return env


def authorize(rules, ctx, kind, segs):
    node = rules.get('rules') if isinstance(rules, dict) else None
    vars_ = {}
    for i in range(len(segs) + 1):
        if not isinstance(node, dict):
            return False
        if '.' + kind in node and eval_rule(node['.' + kind], make_env(ctx, segs[:i], vars_)):
            return True
        if i == len(segs):
            return False
        node, var = rule_child(node, segs[i])
        if var:
            vars_[var] = segs[i]
    return False


def validate_write(rules, ctx, segs, value):
    node = rules.get('rules') if isinstance(rules, dict) else None
    vars_ = {}
    for i in range(len(segs) + 1):
        if not isinstance(node, dict):
            return True
        exists = value is not None if i < len(segs) else value is not None
        if '.validate' in node and exists:
            if not eval_rule(node['.validate'], make_env(ctx, segs[:i], vars_)):
                return False
        if i == len(segs):
            break
        node, var = rule_child(node, segs[i])
        if var:
            vars_[var] = segs[i]
    return _validate_down(node, ctx, segs, vars_, value)


def _validate_down(node, ctx, segs, vars_, value):
    if not isinstance(node, dict) or not isinstance(value, dict):
        return True
    for k, v in value.items():
        child, var = rule_child(node, k)
        if not isinstance(child, dict):
            continue
        vv = dict(vars_)
        if var:
            vv[var] = k
        s2 = segs + [k]
        if '.validate' in child and not eval_rule(child['.validate'], make_env(ctx, s2, vv)):
            return False
        if not _validate_down(child, ctx, s2, vv, v):
            return False
    return True


# ------------------------------------------------------------------ http
class Limiter(object):
    def __init__(self):
        self.h, self.lock = {}, threading.Lock()

    def hit(self, key, limit, per):
        now = time.time()
        with self.lock:
            if len(self.h) > 5000:
                self.h.clear()
            arr = [t for t in self.h.get(key, []) if now - t < per]
            ok = len(arr) < limit
            if ok:
                arr.append(now)
            self.h[key] = arr
            return ok


STORE = HUB = None
LIMIT = Limiter()
STREAMS = threading.BoundedSemaphore(MAX_STREAMS)


def origin_ok(row, origin):
    pats = [p.strip() for p in (row['origins'] or '').replace(',', '\n').split('\n') if p.strip()]
    if not pats:
        return True
    return any(fnmatch.fnmatchcase(origin or '', p) for p in pats)


class Handler(BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'
    disable_nagle_algorithm = True
    server_version = 'AceroRTDB'
    sys_version = ''

    def log_message(self, *a):
        pass

    def ip(self):
        ip = self.client_address[0]
        if ip in ('127.0.0.1', '::1'):
            xf = self.headers.get('X-Forwarded-For', '')
            if xf:
                return xf.split(',')[0].strip()
        return ip

    def cors(self, allow):
        if allow:
            self.send_header('Access-Control-Allow-Origin', allow)
            self.send_header('Vary', 'Origin')
            self.send_header('Access-Control-Allow-Methods', 'GET, PUT, POST, PATCH, DELETE, OPTIONS')
            self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Api-Key, Accept')
            self.send_header('Access-Control-Max-Age', '600')

    def reply(self, code, body=None, allow=None, raw=None, ctype='application/json; charset=utf-8'):
        if code == 204:
            data = b''
        elif raw is not None:
            data = raw
        else:
            data = json.dumps(body, ensure_ascii=False, separators=(',', ':')).encode()
        self.send_response(code)
        if code != 204:
            self.send_header('Content-Type', ctype)
        self.send_header('Content-Length', str(len(data)))
        self.send_header('Cache-Control', 'no-store')
        self.send_header('X-Content-Type-Options', 'nosniff')
        self.cors(allow)
        self.end_headers()
        if data and self.command != 'HEAD':
            self.wfile.write(data)
        return len(data)

    def body_json(self):
        n = int(self.headers.get('Content-Length') or 0)
        if n > MAX_BODY:
            raise ApiError(413, 'Request body is too large')
        raw = self.rfile.read(n) if n else b''
        if not raw.strip():
            return None
        try:
            return json.loads(raw.decode('utf-8'))
        except Exception:
            raise ApiError(400, 'Invalid JSON')

    def do_GET(self): self.handle_any('GET')
    def do_PUT(self): self.handle_any('PUT')
    def do_POST(self): self.handle_any('POST')
    def do_PATCH(self): self.handle_any('PATCH')
    def do_DELETE(self): self.handle_any('DELETE')
    def do_OPTIONS(self): self.handle_any('OPTIONS')

    def handle_any(self, method):
        self._allow = None
        try:
            self.route(method)
        except ApiError as e:
            self.reply(e.code, {'error': e.msg}, allow=self._allow)
        except (BrokenPipeError, ConnectionResetError, TimeoutError):
            self.close_connection = True
        except Exception as e:
            sys.stderr.write('ERR %r\n' % (e,))
            try:
                self.reply(500, {'error': 'Server error'}, allow=self._allow)
            except Exception:
                self.close_connection = True

    def route(self, method):
        u = urlparse(self.path)
        q = dict((k, v[0]) for k, v in parse_qs(u.query, keep_blank_values=True).items())
        origin = self.headers.get('Origin')
        p = u.path
        if p == '/health':
            return self.reply(200, {'ok': True, 'v': VERSION})
        if p == '/sdk.js':
            try:
                with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sdk.js'), 'rb') as f:
                    js = f.read()
            except OSError:
                raise ApiError(404, 'SDK not installed')
            self.send_response(200)
            self.send_header('Content-Type', 'application/javascript; charset=utf-8')
            self.send_header('Content-Length', str(len(js)))
            self.send_header('Cache-Control', 'public, max-age=300')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('X-Content-Type-Options', 'nosniff')
            self.end_headers()
            self.wfile.write(js)
            return
        if p.startswith('/_auth/'):
            return self.auth_route(method, p, q, origin)
        if not p.endswith('.json'):
            raise ApiError(404, 'Not found')
        parts = [unquote(x) for x in p[:-5].split('/') if x != '']
        if not parts:
            raise ApiError(404, 'Not found')
        sid, rest = parts[0], parts[1:]
        row = STORE.site(sid)
        if method == 'OPTIONS':
            allow = (origin if row and origin_ok(row, origin) else None) if row else None
            return self.reply(204, allow=allow)
        if not row or not row['enabled']:
            raise ApiError(404, 'Unknown site')
        key = q.get('key') or self.headers.get('X-Api-Key') or ''
        admin = hmac.compare_digest(key, row['secret_key'])
        if not admin and not hmac.compare_digest(key, row['public_key']):
            raise ApiError(401, 'Invalid API key')
        if origin and not admin:
            if not origin_ok(row, origin):
                raise ApiError(403, 'Origin not allowed')
            self._allow = origin
        elif origin:
            self._allow = origin
        for s in rest:
            if not valid_key(s):
                raise ApiError(400, 'Invalid path')
        auth = None
        if not admin:
            tok = q.get('auth') or ''
            hb = self.headers.get('Authorization', '')
            if not tok and hb.startswith('Bearer '):
                tok = hb[7:]
            if tok:
                auth = STORE.check_token(sid, tok)
                if auth is None:
                    raise ApiError(401, 'Invalid or expired auth token')
        if not admin and not LIMIT.hit(('d', self.ip()), 600, 60):
            raise ApiError(429, 'Too many requests')
        rules = row['rules_obj']
        silent = q.get('print') == 'silent'
        path = spath(rest)

        def can(kind, segs, write=None):
            return admin or authorize(rules, Ctx(STORE, sid, auth, write), kind, segs)

        if method == 'GET':
            if not can('read', rest):
                raise ApiError(401, 'Permission denied')
            if 'text/event-stream' in (self.headers.get('Accept') or ''):
                return self.stream(sid, path)
            data = STORE.get(sid, path)
            if q.get('shallow') == 'true' and isinstance(data, dict):
                data = dict((k, True) for k in data)
            n = self.reply(200, data, allow=self._allow)
            STORE.bump(sid, 'r', n)
            return
        if method in ('PUT', 'POST'):
            val = clean(self.body_json())
            segs = rest
            if method == 'POST':
                segs = rest + [push_id()]
            self.check_write(can, rules, sid, auth, admin, segs, val)
            STORE.write(sid, [(spath(segs), val)])
            if silent:
                return self.reply(204, allow=self._allow)
            return self.reply(200, {'name': segs[-1]} if method == 'POST' else val, allow=self._allow)
        if method == 'DELETE':
            self.check_write(can, rules, sid, auth, admin, rest, None)
            STORE.write(sid, [(path, None)])
            return self.reply(204 if silent else 200, None, allow=self._allow)
        if method == 'PATCH':
            body = self.body_json()
            if not isinstance(body, dict) or not body:
                raise ApiError(400, 'PATCH needs a JSON object')
            ops = []
            for k, v in body.items():
                kp = [x for x in k.split('/') if x]
                if not kp or not all(valid_key(x) for x in kp):
                    raise ApiError(400, 'Invalid key: ' + k[:40])
                ops.append((rest + kp, clean(v)))
            for segs, val in ops:
                self.check_write(can, rules, sid, auth, admin, segs, val)
            STORE.write(sid, [(spath(s), v) for s, v in ops])
            return self.reply(204 if silent else 200, body, allow=self._allow)
        raise ApiError(405, 'Method not allowed')

    def check_write(self, can, rules, sid, auth, admin, segs, val):
        if admin:
            return
        if not can('write', segs, (segs, val)):
            raise ApiError(401, 'Permission denied')
        if not validate_write(rules, Ctx(STORE, sid, auth, (segs, val)), segs, val):
            raise ApiError(400, 'Data failed validation')

    def stream(self, sid, path):
        if not STREAMS.acquire(blocking=False):
            raise ApiError(503, 'Too many open streams')
        sub = HUB.subscribe(sid, path)
        try:
            self.send_response(200)
            self.send_header('Content-Type', 'text/event-stream')
            self.send_header('Cache-Control', 'no-cache')
            self.send_header('Connection', 'keep-alive')
            self.send_header('X-Accel-Buffering', 'no')
            self.cors(self._allow)
            self.end_headers()
            self.close_connection = True
            last = None
            sub.tick()
            while True:
                try:
                    sub.q.get(timeout=20)
                except queue.Empty:
                    self.wfile.write(b'event: keep-alive\ndata: null\n\n')
                    self.wfile.flush()
                    continue
                s = json.dumps(STORE.get(sid, path), ensure_ascii=False, separators=(',', ':'))
                if s == last:
                    continue
                last = s
                self.wfile.write(('event: put\ndata: {"path":"/","data":%s}\n\n' % s).encode())
                self.wfile.flush()
                STORE.bump(sid, 'r', len(s))
        finally:
            HUB.unsubscribe(sub)
            STREAMS.release()

    def auth_route(self, method, p, q, origin):
        parts = p.split('/')            # ['', '_auth', site, action]
        if len(parts) != 4:
            raise ApiError(404, 'Not found')
        sid, action = parts[2], parts[3]
        row = STORE.site(sid)
        if method == 'OPTIONS':
            return self.reply(204, allow=origin if row and origin_ok(row, origin) else None)
        if not row or not row['enabled']:
            raise ApiError(404, 'Unknown site')
        if origin:
            if not origin_ok(row, origin):
                raise ApiError(403, 'Origin not allowed')
            self._allow = origin
        key = q.get('key') or self.headers.get('X-Api-Key') or ''
        if not hmac.compare_digest(key, row['public_key']):
            raise ApiError(401, 'Invalid API key')
        if method != 'POST' or action not in ('signup', 'login'):
            raise ApiError(404, 'Not found')
        if not LIMIT.hit(('a', self.ip()), 20, 60):
            raise ApiError(429, 'Too many attempts, try again in a minute')
        b = self.body_json() or {}
        if not isinstance(b, dict):
            raise ApiError(400, 'Invalid JSON')
        if action == 'signup':
            uid, email = STORE.signup(sid, b.get('email'), b.get('password'))
        else:
            uid, email = STORE.login(sid, b.get('email'), b.get('password'))
        self.reply(200, {'uid': uid, 'email': email, 'token': STORE.make_token(sid, uid, email), 'expiresIn': TOKEN_TTL},
                   allow=self._allow)


class Server(ThreadingHTTPServer):
    daemon_threads = True
    request_queue_size = 256
    allow_reuse_address = True


def init(base):
    global STORE, HUB
    STORE = Store(base)
    HUB = Hub(STORE)
    return STORE, HUB


def serve(base, host, port):
    init(base)
    srv = Server((host, port), Handler)
    sys.stderr.write('ACERO RTDB %s on %s:%d (data: %s)\n' % (VERSION, host, port, base))
    try:
        srv.serve_forever()
    finally:
        STORE.flush_usage()


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('cmd', choices=['serve', 'create-site', 'list-sites'])
    ap.add_argument('arg', nargs='?')
    ap.add_argument('--base', default=os.environ.get('RTDB_BASE', '/opt/acero-rtdb/data'))
    ap.add_argument('--host', default='127.0.0.1')
    ap.add_argument('--port', type=int, default=8087)
    a = ap.parse_args()
    if a.cmd == 'serve':
        serve(a.base, a.host, a.port)
    else:
        st, _ = init(a.base)
        if a.cmd == 'create-site':
            r = st.create_site(a.arg)
            print(r['id'], r['public_key'], r['secret_key'])
        else:
            for r in st.sites():
                print(r['id'], r['public_key'])
ACERO_RTDB_PY_EOF

cat > ${APP}/panel.py <<'ACERO_PANEL_PY_EOF'
#!/usr/bin/env python3
"""ACERO REALTIME DB panel + launcher (stdlib only).

  python3 panel.py serve            run the database API and the panel (what the service does)
  python3 panel.py init             create config (secret path) if missing, print the secret path
  PW='newpass' python3 panel.py setpw   set / reset the panel password
"""
import os, sys, re, json, time, hmac, hashlib, secrets, threading, shutil, sqlite3, tempfile, subprocess, argparse
from http.server import BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import rtdb
from rtdb import ApiError, valid_key, spath

PANEL_VER = 'v47'
BASE = os.environ.get('RTDB_BASE', '/opt/acero-rtdb/data')
CFG_FILE = os.path.join(BASE, 'config.json')
SESSION_TTL = 12 * 3600
CFG = {}


# ------------------------------------------------------------------ config + password + sessions
def load_cfg():
    global CFG
    try:
        with open(CFG_FILE) as f:
            CFG = json.load(f)
    except Exception:
        CFG = {}
    return CFG


def save_cfg():
    os.makedirs(BASE, exist_ok=True)
    tmp = CFG_FILE + '.tmp'
    with open(tmp, 'w') as f:
        json.dump(CFG, f, indent=2)
    os.chmod(tmp, 0o600)
    os.replace(tmp, CFG_FILE)


def hash_pw(pw, salt):
    return hashlib.pbkdf2_hmac('sha256', pw.encode(), bytes.fromhex(salt), 200000).hex()


def set_password(pw):
    salt = secrets.token_hex(16)
    CFG['pw_salt'], CFG['pw_hash'] = salt, hash_pw(pw, salt)
    save_cfg()


def check_password(pw):
    if not CFG.get('pw_hash') or not isinstance(pw, str):
        return False
    return hmac.compare_digest(hash_pw(pw, CFG['pw_salt']), CFG['pw_hash'])


def session_sig(exp, nonce):
    msg = ('%s.%s.%s' % (exp, nonce, CFG.get('pw_hash', '')[:16])).encode()
    return hmac.new(rtdb.STORE.secret + b'session', msg, hashlib.sha256).hexdigest()


def new_session():
    exp, nonce = int(time.time()) + SESSION_TTL, secrets.token_hex(8)
    return '%s.%s.%s' % (exp, nonce, session_sig(exp, nonce))


def valid_session(cookie):
    try:
        exp, nonce, sig = cookie.split('.')
        return int(exp) > time.time() and hmac.compare_digest(sig, session_sig(exp, nonce))
    except Exception:
        return False


FAILS = {}
FAIL_LOCK = threading.Lock()


def too_many_fails(ip):
    now = time.time()
    with FAIL_LOCK:
        arr = [t for t in FAILS.get(ip, []) if now - t < 600]
        FAILS[ip] = arr
        return len(arr) >= 8


def add_fail(ip):
    with FAIL_LOCK:
        if len(FAILS) > 2000:
            FAILS.clear()
        FAILS.setdefault(ip, []).append(time.time())


# ------------------------------------------------------------------ server info
_cpu = {'pct': 0.0}


def _cpu_loop():
    def rd():
        try:
            with open('/proc/stat') as f:
                v = [int(x) for x in f.readline().split()[1:]]
            return sum(v), v[3] + (v[4] if len(v) > 4 else 0)
        except Exception:
            return None
    a = rd()
    while True:
        time.sleep(5)
        b = rd()
        if a and b and b[0] > a[0]:
            _cpu['pct'] = round(100.0 * (1 - (b[1] - a[1]) / float(b[0] - a[0])), 1)
        a = b


def svc(name):
    if not shutil.which('systemctl'):
        return 'n/a'
    try:
        r = subprocess.run(['systemctl', 'is-active', name], capture_output=True, text=True, timeout=3)
        return r.stdout.strip() or 'unknown'
    except Exception:
        return 'n/a'


def server_info():
    mem = {}
    try:
        with open('/proc/meminfo') as f:
            for line in f:
                k, v = line.split(':')
                mem[k] = int(v.split()[0]) * 1024
    except Exception:
        pass
    up = 0
    try:
        with open('/proc/uptime') as f:
            up = int(float(f.read().split()[0]))
    except Exception:
        pass
    du = shutil.disk_usage(BASE if os.path.isdir(BASE) else '/')
    dbsize = 0
    for suf in ('', '-wal', '-shm'):
        try:
            dbsize += os.path.getsize(os.path.join(BASE, 'rtdb.sqlite3' + suf))
        except OSError:
            pass
    try:
        load = os.getloadavg()
    except OSError:
        load = (0, 0, 0)
    return {'cpu': _cpu['pct'], 'mem_total': mem.get('MemTotal', 0), 'mem_avail': mem.get('MemAvailable', 0),
            'disk_total': du.total, 'disk_used': du.used, 'uptime': up, 'load': [round(x, 2) for x in load],
            'db_bytes': dbsize, 'streams': rtdb.HUB.count(), 'engine': rtdb.VERSION, 'panel': PANEL_VER,
            'python': sys.version.split()[0],
            'services': {'acero-rtdb': svc('acero-rtdb'), 'nginx': svc('nginx')}}


# ------------------------------------------------------------------ data browser (admin)
CHILD_SQL = '''SELECT k, count(*), max(CASE WHEN rel = k THEN val END) FROM (
  SELECT val, substr(path, ?1) AS rel,
         substr(substr(path, ?1), 1, instr(substr(path, ?1) || '/', '/') - 1) AS k
  FROM nodes WHERE site=?2 AND path>=?3 AND path<?4) GROUP BY k ORDER BY k LIMIT ?5'''


def parse_path(p):
    segs = [s for s in (p or '').split('/') if s != '']
    for s in segs:
        if not valid_key(s):
            raise ApiError(400, 'Invalid path')
    return segs


def node_info(site, segs):
    st, path = rtdb.STORE, spath(segs)
    with st.lock:
        leaf = st.db.execute('SELECT val FROM nodes WHERE site=? AND path=?', (site, path)).fetchone() if path else None
        if leaf:
            return {'kind': 'leaf', 'value': json.loads(leaf[0])}
        n, size = st.db.execute('SELECT count(*), coalesce(sum(length(val)+length(path)),0) FROM nodes WHERE site=? AND path>=? AND path<?',
                                (site, path + '/', path + '0')).fetchone()
        if n == 0:
            return {'kind': 'empty'}
        rows = st.db.execute(CHILD_SQL, (len(path) + 2, site, path + '/', path + '0', 201)).fetchall()
    kids = [{'k': k, 'n': c, 'leaf': (json.loads(lv) if lv is not None else None), 'is_leaf': lv is not None} for k, c, lv in rows[:200]]
    out = {'kind': 'object', 'leaves': n, 'bytes': size, 'children': kids, 'truncated': len(rows) > 200}
    if size <= 300000:
        out['value'] = st.get(site, path)
    return out


def simulate(row, body):
    op = body.get('op')
    segs = parse_path(body.get('path'))
    uid = (body.get('uid') or '').strip()
    auth = {'uid': uid, 'email': (body.get('email') or '').strip()} if uid else None
    rules = row['rules_obj']
    if op == 'read':
        ctx = rtdb.Ctx(rtdb.STORE, row['id'], auth)
        ok = rtdb.authorize(rules, ctx, 'read', segs)
        return {'allowed': ok, 'reason': '' if ok else 'No .read rule grants access at this path.'}
    if op == 'write':
        try:
            val = rtdb.clean(json.loads(body.get('value') or 'null'))
        except ValueError:
            raise ApiError(400, 'The value is not valid JSON')
        ctx = rtdb.Ctx(rtdb.STORE, row['id'], auth, (segs, val))
        if not rtdb.authorize(rules, ctx, 'write', segs):
            return {'allowed': False, 'reason': 'No .write rule grants access at this path.'}
        if not rtdb.validate_write(rules, ctx, segs, val):
            return {'allowed': False, 'reason': 'Blocked by a .validate rule.'}
        return {'allowed': True, 'reason': ''}
    raise ApiError(400, 'op must be read or write')


def need_site(sid):
    row = rtdb.STORE.site(sid)
    if not row:
        raise ApiError(404, 'Unknown site')
    return row


def site_public(row):
    return {'id': row['id'], 'name': row['name'], 'enabled': bool(row['enabled']), 'origins': row['origins'] or '',
            'public_key': row['public_key'], 'secret_key': row['secret_key'], 'rules': row['rules'], 'created': row['created']}


def make_backup():
    fd, tmp = tempfile.mkstemp(prefix='acero-bk-', suffix='.sqlite3')
    os.close(fd)
    dst = sqlite3.connect(tmp)
    with rtdb.STORE.lock:
        rtdb.STORE.db.backup(dst)
    dst.close()
    with open(tmp, 'rb') as f:
        data = f.read()
    os.remove(tmp)
    return data


# ------------------------------------------------------------------ http
class PanelHandler(BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'
    disable_nagle_algorithm = True
    server_version = 'AceroPanel'
    sys_version = ''

    def log_message(self, *a):
        pass

    def ip(self):
        ip = self.client_address[0]
        if ip in ('127.0.0.1', '::1'):
            xf = self.headers.get('X-Forwarded-For', '')
            if xf:
                return xf.split(',')[0].strip()
        return ip

    def send(self, code, data, ctype, extra=None):
        self.send_response(code)
        self.send_header('Content-Type', ctype)
        self.send_header('Content-Length', str(len(data)))
        self.send_header('Cache-Control', 'no-store')
        self.send_header('X-Content-Type-Options', 'nosniff')
        self.send_header('X-Frame-Options', 'DENY')
        self.send_header('Referrer-Policy', 'no-referrer')
        self.send_header('X-Robots-Tag', 'noindex, nofollow')
        for k, v in (extra or []):
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(data)

    def jr(self, code, obj, extra=None):
        self.send(code, json.dumps(obj, ensure_ascii=False, separators=(',', ':')).encode(), 'application/json; charset=utf-8', extra)

    def body(self):
        n = int(self.headers.get('Content-Length') or 0)
        if n > 6 * 1024 * 1024:
            raise ApiError(413, 'Request body is too large')
        raw = self.rfile.read(n) if n else b''
        if not raw.strip():
            return {}
        try:
            j = json.loads(raw.decode('utf-8'))
        except Exception:
            raise ApiError(400, 'Invalid JSON')
        if not isinstance(j, dict):
            raise ApiError(400, 'Expected a JSON object')
        return j

    def do_GET(self): self.dispatch('GET')
    def do_POST(self): self.dispatch('POST')

    def dispatch(self, method):
        try:
            self.route(method)
        except ApiError as e:
            self.jr(e.code, {'error': e.msg})
        except (BrokenPipeError, ConnectionResetError, TimeoutError):
            self.close_connection = True
        except Exception as e:
            sys.stderr.write('PANEL ERR %r\n' % (e,))
            try:
                self.jr(500, {'error': 'Server error'})
            except Exception:
                self.close_connection = True

    def cookie(self):
        for part in (self.headers.get('Cookie') or '').split(';'):
            k, _, v = part.strip().partition('=')
            if k == 'acero_s':
                return v
        return ''

    def public_url(self):
        if CFG.get('public_url'):
            return CFG['public_url'].rstrip('/')
        proto = self.headers.get('X-Forwarded-Proto') or 'http'
        return '%s://%s' % (proto, self.headers.get('Host') or 'localhost')

    def route(self, method):
        u = urlparse(self.path)
        p = u.path
        q = dict((k, v[0]) for k, v in parse_qs(u.query).items())
        secret = CFG.get('secret') or ''
        pref = '/%s/panel' % secret
        if not secret:
            return self.send(404, b'Not found', 'text/plain')
        if p == '/' + secret or p == pref:
            return self.send(301, b'', 'text/plain', [('Location', pref + '/')])
        if not p.startswith(pref + '/'):
            return self.send(404, b'Not found', 'text/plain')
        rest = p[len(pref) + 1:]
        if rest == '' and method == 'GET':
            csp = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
            return self.send(200, UI_HTML.replace('__VER__', PANEL_VER).encode(), 'text/html; charset=utf-8', [('Content-Security-Policy', csp)])
        if not rest.startswith('api/'):
            return self.send(404, b'Not found', 'text/plain')
        api = rest[4:]
        secure = (self.headers.get('X-Forwarded-Proto') == 'https')
        if api == 'login' and method == 'POST':
            if self.headers.get('X-Panel') != '1':
                raise ApiError(403, 'Forbidden')
            ip = self.ip()
            if too_many_fails(ip):
                raise ApiError(429, 'Too many wrong passwords. Try again in 10 minutes.')
            if not check_password(self.body().get('password')):
                add_fail(ip)
                time.sleep(0.6)
                raise ApiError(401, 'Wrong password')
            ck = 'acero_s=%s; Path=%s/; HttpOnly; SameSite=Strict; Max-Age=%d%s' % (new_session(), pref, SESSION_TTL, '; Secure' if secure else '')
            return self.jr(200, {'ok': True}, [('Set-Cookie', ck)])
        if api == 'me':
            return self.jr(200, {'ok': valid_session(self.cookie()), 'ver': PANEL_VER})
        if not valid_session(self.cookie()):
            raise ApiError(401, 'Not signed in')
        if api == 'logout' and method == 'POST':
            return self.jr(200, {'ok': True}, [('Set-Cookie', 'acero_s=; Path=%s/; HttpOnly; SameSite=Strict; Max-Age=0' % pref)])
        if method == 'POST' and self.headers.get('X-Panel') != '1':
            raise ApiError(403, 'Forbidden')
        st = rtdb.STORE
        if api == 'overview':
            st.flush_usage()
            out = []
            for row in st.sites():
                s = st.site_stats(row['id'])
                today = s['usage'][0] if s['usage'] else None
                out.append({'id': row['id'], 'name': row['name'], 'enabled': bool(row['enabled']), 'nodes': s['nodes'], 'bytes': s['bytes'],
                            'users': s['users'], 'reads': today[1] if today else 0, 'writes': today[2] if today else 0})
            return self.jr(200, {'sites': out, 'base_url': self.public_url()})
        if api == 'site' and method == 'GET':
            st.flush_usage()
            row = need_site(q.get('id'))
            return self.jr(200, {'site': site_public(row), 'stats': st.site_stats(row['id']), 'base_url': self.public_url()})
        if api == 'site/create' and method == 'POST':
            b = self.body()
            row = st.create_site(str(b.get('id') or '').strip().lower(), str(b.get('name') or '').strip()[:60], str(b.get('origins') or '')[:2000])
            return self.jr(200, {'id': row['id']})
        if api == 'site/update' and method == 'POST':
            b = self.body()
            row = need_site(b.get('id'))
            kw = {}
            if 'name' in b:
                kw['name'] = str(b['name']).strip()[:60] or row['id']
            if 'origins' in b:
                kw['origins'] = str(b['origins'])[:2000]
            if 'enabled' in b:
                kw['enabled'] = 1 if b['enabled'] else 0
            st.update_site(row['id'], **kw)
            return self.jr(200, {'ok': True})
        if api == 'site/rules' and method == 'POST':
            b = self.body()
            st.set_rules(need_site(b.get('id'))['id'], str(b.get('rules') or ''))
            return self.jr(200, {'ok': True})
        if api == 'site/simulate' and method == 'POST':
            b = self.body()
            return self.jr(200, simulate(need_site(b.get('id')), b))
        if api == 'site/rotate' and method == 'POST':
            b = self.body()
            row = need_site(b.get('id'))
            if b.get('which') not in ('public', 'secret'):
                raise ApiError(400, 'which must be public or secret')
            return self.jr(200, {'key': st.rotate_key(row['id'], b['which'])})
        if api == 'site/delete' and method == 'POST':
            b = self.body()
            row = need_site(b.get('id'))
            if b.get('confirm') != row['id']:
                raise ApiError(400, 'Type the site id to confirm')
            st.delete_site(row['id'])
            return self.jr(200, {'ok': True})
        if api == 'data' and method == 'GET':
            row = need_site(q.get('site'))
            return self.jr(200, node_info(row['id'], parse_path(q.get('path'))))
        if api == 'data' and method == 'POST':
            b = self.body()
            row = need_site(b.get('site'))
            segs = parse_path(b.get('path'))
            mode = b.get('mode')
            if mode == 'delete':
                st.write(row['id'], [(spath(segs), None)])
                return self.jr(200, {'ok': True})
            val = rtdb.clean(b.get('value'))
            if mode == 'push':
                segs = segs + [rtdb.push_id()]
            elif mode != 'set':
                raise ApiError(400, 'Unknown mode')
            st.write(row['id'], [(spath(segs), val)])
            return self.jr(200, {'ok': True, 'path': spath(segs)})
        if api == 'export' and method == 'GET':
            row = need_site(q.get('site'))
            data = json.dumps(st.get(row['id'], ''), ensure_ascii=False, indent=1).encode()
            fn = '%s-export-%s.json' % (row['id'], time.strftime('%Y%m%d-%H%M', time.gmtime()))
            return self.send(200, data, 'application/json', [('Content-Disposition', 'attachment; filename="%s"' % fn)])
        if api == 'users' and method == 'GET':
            row = need_site(q.get('site'))
            return self.jr(200, {'users': [{'uid': a, 'email': b, 'created': c} for a, b, c in st.users(row['id'])]})
        if api == 'user/delete' and method == 'POST':
            b = self.body()
            st.delete_user(need_site(b.get('site'))['id'], str(b.get('uid') or ''))
            return self.jr(200, {'ok': True})
        if api == 'server' and method == 'GET':
            return self.jr(200, server_info())
        if api == 'backup' and method == 'GET':
            fn = 'acero-rtdb-backup-%s.sqlite3' % time.strftime('%Y%m%d-%H%M', time.gmtime())
            return self.send(200, make_backup(), 'application/octet-stream', [('Content-Disposition', 'attachment; filename="%s"' % fn)])
        if api == 'password' and method == 'POST':
            b = self.body()
            if not check_password(b.get('old')):
                raise ApiError(401, 'Current password is wrong')
            new = b.get('new')
            if not isinstance(new, str) or len(new) < 8 or len(new) > 100:
                raise ApiError(400, 'New password must be 8-100 characters')
            set_password(new)
            ck = 'acero_s=%s; Path=%s/; HttpOnly; SameSite=Strict; Max-Age=%d%s' % (new_session(), pref, SESSION_TTL, '; Secure' if secure else '')
            return self.jr(200, {'ok': True}, [('Set-Cookie', ck)])
        raise ApiError(404, 'Not found')


# ------------------------------------------------------------------ UI (English, mobile first)
UI_HTML = r'''<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>ACERO REALTIME DB</title><meta name="robots" content="noindex,nofollow"><meta name="theme-color" content="#0f1526">
<style>
:root{--bg:#0f1526;--panel:#172039;--code:#0a0f1d;--line:#2a3556;--text:#e9edf7;--muted:#a8b2cc;--amber:#ffc83d;--ok:#4cd6a0;--bad:#ff6b6b;--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
*{box-sizing:border-box}html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;overflow-wrap:anywhere}
a{color:var(--amber)}button,input,select,textarea{font:inherit;color:inherit}
header{position:sticky;top:0;z-index:5;display:flex;align-items:center;justify-content:space-between;gap:.5rem;padding:.55rem .9rem;background:rgba(15,21,38,.97);border-bottom:1px solid var(--line)}
header b{color:var(--amber);letter-spacing:-.01em}header nav{display:flex;gap:.4rem}
main{max-width:62rem;margin:0 auto;padding:1rem .9rem 4rem}
h1{font-size:1.25rem;margin:.2rem 0 .8rem}h2{font-size:1.02rem;margin:1.2rem 0 .5rem}
.card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:.8rem .9rem;margin:.6rem 0}
.row{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center}.grow{flex:1 1 12rem;min-width:0}
a.btn{text-decoration:none;display:inline-block}
.btn{background:var(--amber);color:#1a1300;border:0;border-radius:9px;padding:.5rem .85rem;font-weight:700;cursor:pointer}
.btn.alt{background:var(--panel);color:var(--text);border:1px solid var(--line);font-weight:600}
.btn.bad{background:transparent;color:var(--bad);border:1px solid var(--bad)}.btn.sm{padding:.3rem .6rem;font-size:.85rem}
.btn:disabled{opacity:.5}
input,select,textarea{width:100%;background:var(--code);border:1px solid var(--line);border-radius:9px;padding:.5rem .65rem}
textarea{font-family:var(--mono);font-size:.85rem;min-height:11rem;resize:vertical}
label{display:block;font-size:.82rem;color:var(--muted);margin:.55rem 0 .2rem}
pre{background:var(--code);border:1px solid var(--line);border-radius:10px;padding:.7rem;overflow-x:auto;font:.8rem/1.45 var(--mono);margin:.4rem 0;white-space:pre}
code{font-family:var(--mono);font-size:.85em;background:var(--code);padding:.05rem .3rem;border-radius:5px}
.tabs{display:flex;gap:.3rem;overflow-x:auto;padding-bottom:.3rem;margin:.4rem 0}
.tabs a{flex:0 0 auto;padding:.4rem .8rem;border-radius:9px;border:1px solid var(--line);text-decoration:none;color:var(--muted);background:var(--panel)}
.tabs a.on{color:#1a1300;background:var(--amber);border-color:var(--amber);font-weight:700}
.muted{color:var(--muted)}.ok{color:var(--ok)}.bad{color:var(--bad)}.small{font-size:.82rem}
.list{display:grid;gap:.5rem}.item{display:block;background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:.7rem .9rem;text-decoration:none;color:var(--text)}
.item b{color:var(--amber)}.pill{display:inline-block;font-size:.72rem;padding:.05rem .5rem;border-radius:99px;border:1px solid var(--line);color:var(--muted)}
.tw{overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:.88rem}th,td{text-align:left;padding:.35rem .5rem;border-bottom:1px solid var(--line);vertical-align:top}
tr.go{cursor:pointer}tr.go:hover{background:rgba(255,200,61,.06)}
.crumbs{font:.85rem var(--mono);margin:.3rem 0}.crumbs a{text-decoration:none}
#toast{position:fixed;left:50%;bottom:1.2rem;transform:translateX(-50%);max-width:92vw;background:#000c;border:1px solid var(--line);padding:.55rem .9rem;border-radius:10px;z-index:9;display:none}
.login{max-width:22rem;margin:18vh auto 0}
.bar{height:8px;background:var(--code);border-radius:6px;overflow:hidden}.bar i{display:block;height:100%;background:var(--amber)}
</style></head><body>
<header><b>ACERO REALTIME DB</b><nav id="nav" hidden><a class="btn alt sm" href="#/sites">Sites</a><a class="btn alt sm" href="#/server">Server</a><button class="btn alt sm" data-act="logout">Log out</button></nav></header>
<main id="app"></main><div id="toast"></div>
<script>
(function(){
var API = location.pathname.replace(/\/$/, '') + '/api/';
var $ = function(s){ return document.querySelector(s); };
var app = $('#app'), nav = $('#nav'), S = { path: '' };
function esc(s){ return String(s == null ? '' : s).replace(/[&<>"']/g, function(c){ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]; }); }
function toast(m, bad){ var t = $('#toast'); t.textContent = m; t.style.color = bad ? '#ff9a9a' : '#e9edf7'; t.style.display = 'block'; clearTimeout(toast.t); toast.t = setTimeout(function(){ t.style.display = 'none'; }, 3200); }
function fmtB(n){ n = n || 0; var u = ['B','KB','MB','GB','TB'], i = 0; while (n >= 1024 && i < 4) { n /= 1024; i++; } return (i ? n.toFixed(1) : n) + ' ' + u[i]; }
function fmtT(s){ var d = Math.floor(s/86400), h = Math.floor(s%86400/3600), m = Math.floor(s%3600/60); return (d ? d + 'd ' : '') + h + 'h ' + m + 'm'; }
function api(path, body){
  var o = { credentials: 'same-origin', headers: { 'X-Panel': '1' } };
  if (body !== undefined) { o.method = 'POST'; o.headers['Content-Type'] = 'application/json'; o.body = JSON.stringify(body); }
  return fetch(API + path, o).then(function(r){ return r.json().catch(function(){ return null; }).then(function(j){
    if (r.status === 401 && path !== 'login') { showLogin(); throw new Error('Signed out'); }
    if (!r.ok) throw new Error((j && j.error) || ('HTTP ' + r.status));
    return j; }); });
}
function copy(text){
  function fb(){ var t = document.createElement('textarea'); t.value = text; t.style.cssText = 'position:fixed;opacity:0'; document.body.appendChild(t); t.select(); try { document.execCommand('copy'); } catch(e){} document.body.removeChild(t); toast('Copied'); }
  if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(function(){ toast('Copied'); }, fb); else fb();
}
function fail(e){ if (e.message !== 'Signed out') toast(e.message, true); }

function showLogin(){
  nav.hidden = true;
  app.innerHTML = '<div class="login card"><h1>Sign in</h1><label for="pw">Panel password</label><input id="pw" type="password" autocomplete="current-password"><div style="margin-top:.8rem"><button class="btn" data-act="login">Sign in</button></div></div>';
  var i = $('#pw'); if (i) { i.focus(); i.addEventListener('keydown', function(e){ if (e.key === 'Enter') act.login(); }); }
}
var act = {
  login: function(){ api('login', { password: $('#pw').value }).then(function(){ nav.hidden = false; route(); }).catch(fail); },
  logout: function(){ api('logout', {}).then(showLogin, showLogin); },
  copy: function(b){ copy(b.dataset.v); },
  reveal: function(b){ var el = $('#sk'); el.textContent = el.dataset.v; b.remove(); },
  create: function(){ api('site/create', { id: $('#nid').value, name: $('#nname').value, origins: $('#norig').value }).then(function(r){ toast('Site created. Rules are locked until you change them.'); location.hash = '#/site/' + r.id + '/keys'; }).catch(fail); },
  savesite: function(b){ api('site/update', { id: b.dataset.id, name: $('#sname').value, origins: $('#sorig').value, enabled: $('#senabled').checked }).then(function(){ toast('Saved'); }).catch(fail); },
  rotate: function(b){ if (!confirm('Make a new ' + b.dataset.which + ' key? The old key stops working immediately.')) return; api('site/rotate', { id: b.dataset.id, which: b.dataset.which }).then(function(){ toast('New key made'); route(); }).catch(fail); },
  delsite: function(b){ var c = prompt('This deletes ALL data, users and keys of this site.\nType the site id (' + b.dataset.id + ') to confirm:'); if (c === null) return; api('site/delete', { id: b.dataset.id, confirm: c }).then(function(){ toast('Site deleted'); location.hash = '#/sites'; }).catch(fail); },
  saverules: function(b){ api('site/rules', { id: b.dataset.id, rules: $('#rules').value }).then(function(){ toast('Rules saved'); }).catch(fail); },
  preset: function(){ var v = $('#preset').value; if (v && PRESETS[v]) $('#rules').value = PRESETS[v]; },
  sim: function(b){ api('site/simulate', { id: b.dataset.id, op: $('#sop').value, path: $('#spath').value, value: $('#sval').value, uid: $('#suid').value }).then(function(r){ var o = $('#sres'); o.className = r.allowed ? 'ok' : 'bad'; o.textContent = r.allowed ? 'Allowed' : 'Denied. ' + r.reason; }).catch(fail); },
  nav: function(b){ S.path = b.dataset.path; route(); },
  rowgo: function(b){ S.path = b.dataset.path; route(); },
  savenode: function(b){ var v; try { v = JSON.parse($('#nodeval').value); } catch(e){ return toast('Not valid JSON: ' + e.message, true); } if (S.path === '' && !confirm('Replace EVERYTHING in this site with this JSON?')) return; api('data', { site: b.dataset.id, path: S.path, mode: 'set', value: v }).then(function(){ toast('Saved'); route(); }).catch(fail); },
  delnode: function(b){ if (!confirm('Delete ' + (S.path || '/') + ' and everything under it?')) return; api('data', { site: b.dataset.id, path: S.path, mode: 'delete' }).then(function(){ S.path = S.path.split('/').slice(0, -1).join('/'); toast('Deleted'); route(); }).catch(fail); },
  addchild: function(b){ var k = $('#ckey').value.trim(), v; if (!k) return toast('Enter a key', true); try { v = JSON.parse($('#cval').value || 'null'); } catch(e){ return toast('Not valid JSON: ' + e.message, true); } api('data', { site: b.dataset.id, path: S.path + '/' + k, mode: 'set', value: v }).then(function(){ toast('Saved'); route(); }).catch(fail); },
  pushchild: function(b){ var v; try { v = JSON.parse($('#cval').value || 'null'); } catch(e){ return toast('Not valid JSON: ' + e.message, true); } api('data', { site: b.dataset.id, path: S.path, mode: 'push', value: v }).then(function(){ toast('Pushed'); route(); }).catch(fail); },
  deluser: function(b){ if (!confirm('Delete this user?')) return; api('user/delete', { site: b.dataset.id, uid: b.dataset.uid }).then(function(){ route(); }).catch(fail); },
  chpw: function(){ api('password', { old: $('#oldpw').value, 'new': $('#newpw').value }).then(function(){ toast('Password changed'); $('#oldpw').value = ''; $('#newpw').value = ''; }).catch(fail); }
};
document.addEventListener('click', function(e){ var b = e.target.closest('[data-act]'); if (b && act[b.dataset.act]) { e.preventDefault(); act[b.dataset.act](b); } });

var PRESETS = {
  locked: '{\n  "rules": {\n    ".read": false,\n    ".write": false\n  }\n}',
  publicread: '{\n  "rules": {\n    ".read": true,\n    ".write": false\n  }\n}',
  open: '{\n  "rules": {\n    ".read": true,\n    ".write": true\n  }\n}',
  signedin: '{\n  "rules": {\n    ".read": "auth != null",\n    ".write": "auth != null"\n  }\n}',
  peruser: '{\n  "rules": {\n    "public": { ".read": true, ".write": false },\n    "users": {\n      "$uid": {\n        ".read": "auth != null && auth.uid == $uid",\n        ".write": "auth != null && auth.uid == $uid"\n      }\n    }\n  }\n}',
  guestbook: '{\n  "rules": {\n    "messages": {\n      ".read": true,\n      "$id": {\n        ".write": "!data.exists()",\n        ".validate": "newData.hasChildren([\'name\', \'text\']) && newData.child(\'text\').val().length < 200"\n      }\n    }\n  }\n}'
};

function tabs(id, cur){
  var t = [['data','Data'],['rules','Rules'],['keys','Keys & Connect'],['users','Users'],['usage','Usage']];
  return '<div class="tabs">' + t.map(function(x){ return '<a href="#/site/' + id + '/' + x[0] + '"' + (x[0] === cur ? ' class="on"' : '') + '>' + x[1] + '</a>'; }).join('') + '</div>';
}
function btn(label, a, attrs, cls){ return '<button class="btn ' + (cls || '') + '" data-act="' + a + '" ' + (attrs || '') + '>' + label + '</button>'; }

function viewSites(){
  api('overview').then(function(o){
    var h = '<h1>Sites</h1><p class="muted small">One site = one website with its own database, keys and rules. API address: <code>' + esc(o.base_url) + '</code></p><div class="list">';
    o.sites.forEach(function(s){ h += '<a class="item" href="#/site/' + esc(s.id) + '/data"><b>' + esc(s.name) + '</b> <span class="pill">' + esc(s.id) + '</span>' + (s.enabled ? '' : ' <span class="pill bad">disabled</span>') + '<div class="muted small">' + s.nodes + ' values &middot; ' + fmtB(s.bytes) + ' &middot; ' + s.users + ' users &middot; today ' + s.reads + ' reads / ' + s.writes + ' writes</div></a>'; });
    if (!o.sites.length) h += '<div class="card muted">No site yet. Make your first one below.</div>';
    h += '</div><h2>New site</h2><div class="card"><label for="nid">Site id (a-z, 0-9, dash)</label><input id="nid" placeholder="myshop" autocapitalize="none"><label for="nname">Name (optional)</label><input id="nname" placeholder="My Shop"><label for="norig">Allowed websites (optional, one per line, example https://myshop.pages.dev)</label><textarea id="norig" style="min-height:4rem"></textarea><div style="margin-top:.7rem">' + btn('Create site', 'create') + '</div></div>';
    app.innerHTML = h;
  }).catch(fail);
}

function viewSite(id, tab){
  api('site?id=' + encodeURIComponent(id)).then(function(r){
    var s = r.site, base = r.base_url, h = '<h1>' + esc(s.name) + ' <span class="pill">' + esc(s.id) + '</span></h1>' + tabs(s.id, tab);
    if (tab === 'data') return viewData(s, h);
    if (tab === 'rules') h += rulesTab(s);
    else if (tab === 'keys') h += keysTab(s, base);
    else if (tab === 'users') return viewUsers(s, h);
    else h += usageTab(r.stats);
    app.innerHTML = h;
  }).catch(fail);
}

function viewData(s, h){
  api('data?site=' + encodeURIComponent(s.id) + '&path=' + encodeURIComponent(S.path)).then(function(n){
    var segs = S.path.split('/').filter(Boolean), acc = '', crumbs = '<a href="#" data-act="nav" data-path="">/ (root)</a>';
    segs.forEach(function(g){ acc += '/' + g; crumbs += ' / <a href="#" data-act="nav" data-path="' + esc(acc) + '">' + esc(g) + '</a>'; });
    h += '<div class="crumbs">' + crumbs + '</div>';
    var id = 'data-id="' + esc(s.id) + '"';
    if (n.kind === 'object') {
      h += '<div class="card tw"><table><tr><th>Key</th><th>Value</th></tr>';
      n.children.forEach(function(c){
        var p = esc(S.path + '/' + c.k);
        h += '<tr class="go" data-act="rowgo" data-path="' + p + '"><td><b>' + esc(c.k) + '</b></td><td>' + (c.is_leaf ? esc(JSON.stringify(c.leaf)).slice(0, 120) : '<span class="muted">{ ' + c.n + ' value' + (c.n === 1 ? '' : 's') + ' }</span>') + '</td></tr>';
      });
      h += '</table>' + (n.truncated ? '<p class="muted small">Showing the first 200 keys.</p>' : '') + '</div>';
    }
    var cur = n.kind === 'empty' ? 'null' : JSON.stringify(n.kind === 'leaf' ? n.value : n.value, null, 2);
    h += '<h2>Edit this location</h2><div class="card">';
    if (n.kind === 'object' && n.value === undefined) h += '<p class="muted small">This location is large (' + fmtB(n.bytes) + '). Open a child to edit it.</p>';
    else h += '<textarea id="nodeval" spellcheck="false">' + esc(cur) + '</textarea><div class="row" style="margin-top:.6rem">' + btn('Save here', 'savenode', id) + btn('Delete here', 'delnode', id, 'bad') + '<a class="btn alt" href="' + API + 'export?site=' + encodeURIComponent(s.id) + '">Export all (JSON)</a></div>';
    h += '</div><h2>Add a child here</h2><div class="card"><div class="row"><div class="grow"><label for="ckey">Key</label><input id="ckey" autocapitalize="none" placeholder="item1"></div></div><label for="cval">Value (JSON)</label><textarea id="cval" style="min-height:5rem" spellcheck="false">{"name": "Example"}</textarea><div class="row" style="margin-top:.6rem">' + btn('Add with this key', 'addchild', id) + btn('Push (auto key)', 'pushchild', id, 'alt') + '</div></div>';
    app.innerHTML = h;
  }).catch(fail);
}

function rulesTab(s){
  var h = '<div class="card"><div class="row"><select id="preset" class="grow"><option value="">Load an example...</option><option value="locked">Locked (nobody but you)</option><option value="publicread">Public read, no public write</option><option value="open">Open to everyone (testing only)</option><option value="signedin">Signed-in users only</option><option value="peruser">Each user owns users/$uid</option><option value="guestbook">Guestbook (public append, validated)</option></select>' + btn('Load', 'preset', '', 'alt') + '</div>';
  h += '<label for="rules">Rules (JSON)</label><textarea id="rules" spellcheck="false" style="min-height:16rem">' + esc(s.rules) + '</textarea><div style="margin-top:.6rem">' + btn('Save rules', 'saverules', 'data-id="' + esc(s.id) + '"') + '</div>';
  h += '<p class="muted small">Your secret key ignores rules. Rules apply to the public key. A <code>.read</code> / <code>.write</code> that is true also covers everything below it. <code>.validate</code> checks the data being written. Variables: <code>auth</code> (null or {uid,email}), <code>data</code>, <code>newData</code>, <code>root</code>, <code>now</code> and <code>$wildcards</code>.</p></div>';
  h += '<h2>Try a rule</h2><div class="card"><div class="row"><div><label for="sop">Action</label><select id="sop"><option>read</option><option>write</option></select></div><div class="grow"><label for="spath">Path</label><input id="spath" placeholder="/users/abc" autocapitalize="none"></div></div><label for="suid">Signed-in user id (empty = not signed in)</label><input id="suid" autocapitalize="none"><label for="sval">Value to write (JSON, for write)</label><textarea id="sval" style="min-height:4rem" spellcheck="false">{"name":"x","text":"hello"}</textarea><div class="row" style="margin-top:.6rem">' + btn('Test', 'sim', 'data-id="' + esc(s.id) + '"', 'alt') + '<b id="sres"></b></div></div>';
  return h;
}

function keysTab(s, base){
  var pk = s.public_key, id = s.id;
  var sdk = '<script src="' + base + '/sdk.js"></' + 'script>\n<script>\n  var db = AceroDB.init({ url: \'' + base + '\', site: \'' + id + '\', key: \'' + pk + '\' });\n  db.ref(\'messages\').on(\'value\', function (snap) { console.log(snap.val()); });\n  db.ref(\'messages\').push({ name: \'Jerald\', text: \'Hello\' });\n</' + 'script>';
  var rest = 'curl "' + base + '/' + id + '/messages.json?key=' + pk + '"\ncurl -X POST "' + base + '/' + id + '/messages.json?key=' + pk + '" -d \'{"text":"Hello"}\'\n# live stream:\ncurl -N -H "Accept: text/event-stream" "' + base + '/' + id + '/messages.json?key=' + pk + '"';
  var h = '<div class="card"><label>API address</label><div class="row"><code class="grow">' + esc(base + '/' + id + '/') + '</code>' + btn('Copy', 'copy', 'data-v="' + esc(base + '/' + id) + '"', 'alt sm') + '</div>';
  h += '<label>Public key (safe to put in your website; rules protect your data)</label><div class="row"><code class="grow">' + esc(pk) + '</code>' + btn('Copy', 'copy', 'data-v="' + esc(pk) + '"', 'alt sm') + btn('New', 'rotate', 'data-id="' + esc(id) + '" data-which="public"', 'bad sm') + '</div>';
  h += '<label>Secret key (admin; ignores rules; NEVER put it in a website)</label><div class="row"><code class="grow" id="sk" data-v="' + esc(s.secret_key) + '">&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;</code>' + btn('Show', 'reveal', '', 'alt sm') + btn('Copy', 'copy', 'data-v="' + esc(s.secret_key) + '"', 'alt sm') + btn('New', 'rotate', 'data-id="' + esc(id) + '" data-which="secret"', 'bad sm') + '</div></div>';
  h += '<h2>Settings</h2><div class="card"><label for="sname">Name</label><input id="sname" value="' + esc(s.name) + '"><label for="sorig">Allowed websites (one per line, empty = any website; use https://*.example.com for subdomains)</label><textarea id="sorig" style="min-height:5rem" spellcheck="false" autocapitalize="none">' + esc(s.origins) + '</textarea><label><input type="checkbox" id="senabled" style="width:auto" ' + (s.enabled ? 'checked' : '') + '> Site is enabled</label><div class="row" style="margin-top:.6rem">' + btn('Save settings', 'savesite', 'data-id="' + esc(id) + '"') + btn('Delete site', 'delsite', 'data-id="' + esc(id) + '"', 'bad') + '</div><p class="muted small">The allowed-websites list only stops other browsers\' pages from using your public key. It does not stop curl, so keep your rules strict.</p></div>';
  h += '<h2>Connect: JavaScript</h2><div class="card"><pre>' + esc(sdk) + '</pre>' + btn('Copy', 'copy', 'data-v="' + esc(sdk) + '"', 'alt sm') + '</div>';
  h += '<h2>Connect: REST (curl)</h2><div class="card"><pre>' + esc(rest) + '</pre>' + btn('Copy', 'copy', 'data-v="' + esc(rest) + '"', 'alt sm') + '</div>';
  return h;
}

function viewUsers(s, h){
  api('users?site=' + encodeURIComponent(s.id)).then(function(r){
    h += '<p class="muted small">Users who signed up with <code>db.auth.signUp(email, password)</code>. Their id is <code>auth.uid</code> in your rules.</p><div class="card tw"><table><tr><th>Email</th><th>User id</th><th>Joined</th><th></th></tr>';
    r.users.forEach(function(u){ h += '<tr><td>' + esc(u.email) + '</td><td><code>' + esc(u.uid) + '</code></td><td>' + new Date(u.created).toLocaleDateString() + '</td><td>' + btn('Delete', 'deluser', 'data-id="' + esc(s.id) + '" data-uid="' + esc(u.uid) + '"', 'bad sm') + '</td></tr>'; });
    if (!r.users.length) h += '<tr><td colspan="4" class="muted">No users yet.</td></tr>';
    app.innerHTML = h + '</table></div>';
  }).catch(fail);
}

function usageTab(st){
  var h = '<div class="card"><p>' + st.nodes + ' stored values &middot; ' + fmtB(st.bytes) + ' &middot; ' + st.users + ' users</p><div class="tw"><table><tr><th>Day (UTC)</th><th>Reads</th><th>Writes</th><th>Data sent</th></tr>';
  st.usage.forEach(function(u){ h += '<tr><td>' + esc(u[0]) + '</td><td>' + u[1] + '</td><td>' + u[2] + '</td><td>' + fmtB(u[3]) + '</td></tr>'; });
  if (!st.usage.length) h += '<tr><td colspan="4" class="muted">No traffic yet.</td></tr>';
  return h + '</table></div></div>';
}

function viewServer(){
  api('server').then(function(s){
    var memu = s.mem_total - s.mem_avail, mp = s.mem_total ? Math.round(memu / s.mem_total * 100) : 0, dp = s.disk_total ? Math.round(s.disk_used / s.disk_total * 100) : 0;
    function bar(p){ return '<div class="bar"><i style="width:' + p + '%"></i></div>'; }
    var h = '<h1>Server</h1><div class="card"><div class="row"><b>CPU</b> ' + s.cpu + '%</div>' + bar(s.cpu) + '<div class="row" style="margin-top:.6rem"><b>Memory</b> ' + fmtB(memu) + ' / ' + fmtB(s.mem_total) + '</div>' + bar(mp) + '<div class="row" style="margin-top:.6rem"><b>Disk</b> ' + fmtB(s.disk_used) + ' / ' + fmtB(s.disk_total) + '</div>' + bar(dp) + '</div>';
    h += '<div class="card"><table><tr><td>Uptime</td><td>' + fmtT(s.uptime) + '</td></tr><tr><td>Load</td><td>' + s.load.join(' / ') + '</td></tr><tr><td>Database size</td><td>' + fmtB(s.db_bytes) + '</td></tr><tr><td>Open live listeners</td><td>' + s.streams + '</td></tr><tr><td>Service acero-rtdb</td><td class="' + (s.services['acero-rtdb'] === 'active' ? 'ok' : '') + '">' + esc(s.services['acero-rtdb']) + '</td></tr><tr><td>Service nginx</td><td class="' + (s.services.nginx === 'active' ? 'ok' : '') + '">' + esc(s.services.nginx) + '</td></tr><tr><td>Versions</td><td>panel ' + esc(s.panel) + ', engine ' + esc(s.engine) + ', python ' + esc(s.python) + '</td></tr></table></div>';
    h += '<h2>About</h2><div class="card"><p><b>ACERO REALTIME DB</b> ' + esc(s.panel) + '. Free script by Jerald Acero. It runs on your own server and you keep all your data.</p><div class="row"><a class="btn alt sm" href="https://m.me/61578621986890" target="_blank" rel="noopener noreferrer">Messenger</a><a class="btn alt sm" href="https://www.facebook.com/share/1DmVMABFog/" target="_blank" rel="noopener noreferrer">Facebook</a></div><p class="muted small">Never send your panel password, secret keys or VPS login to anyone.</p></div>';
    h += '<h2>Backup</h2><div class="card"><p class="muted small">Downloads a consistent copy of the whole database (all sites, data and users). Keep it somewhere safe.</p><a class="btn" href="' + API + 'backup">Download backup</a></div>';
    h += '<h2>Change panel password</h2><div class="card"><label for="oldpw">Current password</label><input id="oldpw" type="password" autocomplete="current-password"><label for="newpw">New password (8+ characters)</label><input id="newpw" type="password" autocomplete="new-password"><div style="margin-top:.6rem">' + btn('Change password', 'chpw') + '</div></div>';
    app.innerHTML = h;
  }).catch(fail);
}

function route(){
  var h = location.hash.replace(/^#\/?/, '').split('/');
  nav.hidden = false;
  if (h[0] === 'server') return viewServer();
  if (h[0] === 'site' && h[1]) {
    if (S.site !== h[1]) { S.site = h[1]; S.path = ''; }
    return viewSite(h[1], h[2] || 'data');
  }
  viewSites();
}
window.addEventListener('hashchange', route);
api('me').then(function(r){ if (r && r.ok) route(); else showLogin(); }, showLogin);
})();
</script></body></html>
'''


# ------------------------------------------------------------------ launcher
def init_cfg(api_port=None, panel_port=None, public_url=None):
    load_cfg()
    changed = False
    if not CFG.get('secret'):
        CFG['secret'] = secrets.token_hex(8)
        changed = True
    for k, v, d in (('api_port', api_port, 8087), ('panel_port', panel_port, 8088)):
        if v is not None and CFG.get(k) != v:
            CFG[k] = v
            changed = True
        elif k not in CFG:
            CFG[k] = d
            changed = True
    if public_url is not None and CFG.get('public_url') != public_url:
        CFG['public_url'] = public_url
        changed = True
    if changed:
        save_cfg()
    return CFG


def serve():
    load_cfg()
    if not CFG.get('secret') or not CFG.get('pw_hash'):
        sys.stderr.write('Not set up yet. Run: python3 panel.py init  and  PW=... python3 panel.py setpw\n')
        sys.exit(2)
    rtdb.init(BASE)
    threading.Thread(target=_cpu_loop, daemon=True).start()
    api_srv = rtdb.Server(('127.0.0.1', int(CFG.get('api_port', 8087))), rtdb.Handler)
    pan_srv = rtdb.Server(('127.0.0.1', int(CFG.get('panel_port', 8088))), PanelHandler)
    threading.Thread(target=api_srv.serve_forever, daemon=True).start()
    sys.stderr.write('ACERO REALTIME DB %s: API 127.0.0.1:%s, panel 127.0.0.1:%s, data %s\n' % (PANEL_VER, CFG.get('api_port'), CFG.get('panel_port'), BASE))
    try:
        pan_srv.serve_forever()
    finally:
        rtdb.STORE.flush_usage()


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('cmd', choices=['serve', 'init', 'setpw'])
    ap.add_argument('--base', default=None)
    ap.add_argument('--api-port', type=int, default=None)
    ap.add_argument('--panel-port', type=int, default=None)
    ap.add_argument('--public-url', default=None)
    a = ap.parse_args()
    if a.base:
        BASE = a.base
        CFG_FILE = os.path.join(BASE, 'config.json')
    if a.cmd == 'init':
        c = init_cfg(a.api_port, a.panel_port, a.public_url)
        print(c['secret'])
    elif a.cmd == 'setpw':
        load_cfg()
        pw = os.environ.get('PW', '')
        if len(pw) < 8:
            sys.stderr.write('Set PW to a password of at least 8 characters.\n')
            sys.exit(1)
        if not CFG.get('secret'):
            init_cfg()
        set_password(pw)
        print('Panel password updated.')
    else:
        serve()
ACERO_PANEL_PY_EOF

cat > ${APP}/sdk.js <<'ACERO_SDK_JS_EOF'
/* ACERO REALTIME DB client SDK (no dependencies). Works in browsers and Node 20+.
 *
 *   <script src="https://YOUR-SERVER/sdk.js"></script>
 *   const db = AceroDB.init({ url: 'https://YOUR-SERVER', site: 'myshop', key: 'acero_pk_...' });
 *   db.ref('items').on('value', snap => console.log(snap.val()));
 *   db.ref('items').push({ name: 'Rice', price: 50 });
 *
 * Never put a secret key (acero_sk_...) in website code. Use the public key (acero_pk_...) plus rules.
 */
(function (root) {
  'use strict';

  function AceroError(message, code) {
    var e = new Error(message);
    e.name = 'AceroError';
    e.code = code || 0;
    return e;
  }

  function segs(path) {
    return String(path || '').split('/').filter(function (s) { return s !== ''; });
  }

  function Snapshot(path, value) {
    this._v = value === undefined ? null : value;
    var s = segs(path);
    this.key = s.length ? s[s.length - 1] : null;
    this.path = '/' + s.join('/');
  }
  Snapshot.prototype.val = function () { return this._v; };
  Snapshot.prototype.exists = function () { return this._v !== null; };
  Snapshot.prototype.hasChildren = function () { return this._v !== null && typeof this._v === 'object' && Object.keys(this._v).length > 0; };
  Snapshot.prototype.numChildren = function () { return this.hasChildren() ? Object.keys(this._v).length : 0; };
  Snapshot.prototype.child = function (p) {
    var v = this._v, parts = segs(p);
    for (var i = 0; i < parts.length; i++) {
      if (v !== null && typeof v === 'object' && Object.prototype.hasOwnProperty.call(v, parts[i])) v = v[parts[i]];
      else { v = null; break; }
    }
    return new Snapshot(this.path + '/' + parts.join('/'), v);
  };
  Snapshot.prototype.forEach = function (fn) {
    if (!this.hasChildren()) return false;
    var keys = Object.keys(this._v);
    for (var i = 0; i < keys.length; i++) {
      if (fn(new Snapshot(this.path + '/' + keys[i], this._v[keys[i]])) === true) return true;
    }
    return false;
  };

  function Ref(db, path) {
    this.db = db;
    this.path = segs(path).join('/');
    var s = segs(path);
    this.key = s.length ? s[s.length - 1] : null;
  }
  Ref.prototype.child = function (p) { return new Ref(this.db, this.path + '/' + segs(p).join('/')); };
  Ref.prototype.parent = function () { var s = segs(this.path); return s.length ? new Ref(this.db, s.slice(0, -1).join('/')) : null; };
  Ref.prototype.get = function () {
    var self = this;
    return this.db._req('GET', this.path).then(function (v) { return new Snapshot(self.path, v); });
  };
  Ref.prototype.set = function (value) { return this.db._req('PUT', this.path, value === undefined ? null : value).then(function () {}); };
  Ref.prototype.update = function (obj) { return this.db._req('PATCH', this.path, obj).then(function () {}); };
  Ref.prototype.remove = function () { return this.db._req('DELETE', this.path).then(function () {}); };
  Ref.prototype.push = function (value) {
    var self = this;
    return this.db._req('POST', this.path, value === undefined ? null : value).then(function (r) { return self.child(r.name); });
  };
  Ref.prototype.once = function () { return this.get(); };

  // on('value' | 'child_added' | 'child_changed' | 'child_removed', callback, errorCallback) -> unsubscribe function
  Ref.prototype.on = function (event, cb, errCb) {
    var ref = this, db = this.db, es = null, closed = false, prev = null, first = true;
    if (['value', 'child_added', 'child_changed', 'child_removed'].indexOf(event) < 0) throw AceroError('Unknown event: ' + event);

    function handle(v) {
      if (event === 'value') { cb(new Snapshot(ref.path, v)); return; }
      var a = (prev && typeof prev === 'object') ? prev : {};
      var b = (v && typeof v === 'object') ? v : {};
      var k;
      if (event === 'child_added') { for (k in b) if (!(k in a)) cb(new Snapshot(ref.path + '/' + k, b[k])); }
      else if (event === 'child_changed') { for (k in b) if (k in a && JSON.stringify(a[k]) !== JSON.stringify(b[k])) cb(new Snapshot(ref.path + '/' + k, b[k])); }
      else { for (k in a) if (!(k in b)) cb(new Snapshot(ref.path + '/' + k, a[k])); }
    }

    function open() {
      if (closed) return;
      if (typeof root.EventSource === 'undefined') { if (errCb) errCb(AceroError('EventSource is not available here')); return; }
      es = new root.EventSource(db._url(ref.path));
      es.addEventListener('put', function (e) {
        var m;
        try { m = JSON.parse(e.data); } catch (x) { return; }
        var v = m && m.data !== undefined ? m.data : null;
        handle(v);
        prev = v; first = false;
      });
      es.onerror = function () {
        // EventSource retries by itself. A permission error closes it for good (readyState CLOSED).
        if (es.readyState === 2 && !closed) {
          if (errCb) errCb(AceroError('Listener closed (permission denied or server unreachable)', 401));
        }
      };
    }
    var entry = { restart: function () { if (es) es.close(); prev = null; first = true; open(); }, stop: function () { closed = true; if (es) es.close(); } };
    db._listeners.push(entry);
    open();
    return function off() {
      entry.stop();
      var i = db._listeners.indexOf(entry);
      if (i >= 0) db._listeners.splice(i, 1);
    };
  };

  function Auth(db) {
    this.db = db;
    this.currentUser = null;
    this._cbs = [];
    this._k = 'acero:' + db.site + ':auth';
    try {
      var raw = root.localStorage && root.localStorage.getItem(this._k);
      if (raw) {
        var u = JSON.parse(raw);
        if (u && u.token && u.exp > Date.now()) this.currentUser = u; else root.localStorage.removeItem(this._k);
      }
    } catch (e) { /* storage not available */ }
  }
  Auth.prototype._set = function (u) {
    this.currentUser = u;
    try { if (root.localStorage) { if (u) root.localStorage.setItem(this._k, JSON.stringify(u)); else root.localStorage.removeItem(this._k); } } catch (e) { /* ignore */ }
    this.db._listeners.slice().forEach(function (l) { l.restart(); });
    var self = this;
    this._cbs.slice().forEach(function (cb) { cb(self.currentUser); });
  };
  Auth.prototype._call = function (action, email, password) {
    var self = this;
    return this.db._raw('POST', this.db.url + '/_auth/' + this.db.site + '/' + action + '?key=' + encodeURIComponent(this.db.key), { email: email, password: password })
      .then(function (r) {
        var u = { uid: r.uid, email: r.email, token: r.token, exp: Date.now() + (r.expiresIn - 60) * 1000 };
        self._set(u);
        return u;
      });
  };
  Auth.prototype.signUp = function (email, password) { return this._call('signup', email, password); };
  Auth.prototype.signIn = function (email, password) { return this._call('login', email, password); };
  Auth.prototype.signOut = function () { this._set(null); return Promise.resolve(); };
  Auth.prototype.onAuthChanged = function (cb) {
    this._cbs.push(cb);
    var self = this;
    cb(this.currentUser);
    return function () { var i = self._cbs.indexOf(cb); if (i >= 0) self._cbs.splice(i, 1); };
  };

  function DB(cfg) {
    if (!cfg || !cfg.url || !cfg.site || !cfg.key) throw AceroError('init needs { url, site, key }');
    this.url = String(cfg.url).replace(/\/+$/, '');
    this.site = cfg.site;
    this.key = cfg.key;
    this._listeners = [];
    this.auth = new Auth(this);
  }
  DB.prototype.ref = function (path) { return new Ref(this, path); };
  DB.prototype._url = function (path) {
    var p = segs(path).map(encodeURIComponent).join('/');
    var u = this.url + '/' + this.site + (p ? '/' + p : '') + '.json?key=' + encodeURIComponent(this.key);
    var user = this.auth && this.auth.currentUser;
    if (user && user.token) u += '&auth=' + encodeURIComponent(user.token);
    return u;
  };
  DB.prototype._req = function (method, path, body) { return this._raw(method, this._url(path), body); };
  DB.prototype._raw = function (method, url, body) {
    var opt = { method: method, headers: {} };
    if (body !== undefined) { opt.headers['Content-Type'] = 'application/json'; opt.body = JSON.stringify(body); }
    return root.fetch(url, opt).then(function (res) {
      return res.text().then(function (t) {
        var j = null;
        if (t) { try { j = JSON.parse(t); } catch (e) { j = null; } }
        if (!res.ok) throw AceroError((j && j.error) || ('HTTP ' + res.status), res.status);
        return j;
      });
    });
  };

  var API = { init: function (cfg) { return new DB(cfg); }, Error: AceroError };
  if (typeof module !== 'undefined' && module.exports) module.exports = API;
  root.AceroDB = API;
})(typeof window !== 'undefined' ? window : (typeof globalThis !== 'undefined' ? globalThis : this));
ACERO_SDK_JS_EOF

python3 -m py_compile ${APP}/rtdb.py ${APP}/panel.py

# ---------------------------------------------------------------- 3. configuration
echo "[3/7] Configuring..."
IP="${ACERO_IP:-$(curl -fsS4 --max-time 8 https://api.ipify.org 2>/dev/null || hostname -I | awk '{print $1}')}"
HOST="${DOMAIN:-$IP}"
INIT_ARGS=(--api-port ${API_PORT} --panel-port ${PANEL_PORT})
if [[ $UPGRADE -eq 0 || -n "$DOMAIN" ]]; then INIT_ARGS+=(--public-url "https://${HOST}"); fi
SECRET="$(RTDB_BASE=${DATA} python3 ${APP}/panel.py init "${INIT_ARGS[@]}")"
if [[ $UPGRADE -eq 0 ]]; then
  PW="$PANEL_PW" RTDB_BASE=${DATA} python3 ${APP}/panel.py setpw >/dev/null
fi
PUBLIC_URL="$(python3 -c "import json;print(json.load(open('${DATA}/config.json')).get('public_url',''))")"
HOST="${PUBLIC_URL#https://}"
HOST_IS_IP=0
[[ "$HOST" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] && HOST_IS_IP=1

if [[ "$TEST" == "1" ]]; then
  echo "[TEST] Skipping system user, systemd, nginx and certificates."
  echo "TEST_SECRET=${SECRET} TEST_PW=${PANEL_PW} TEST_URL=${PUBLIC_URL}"
  exit 0
fi

if ! id -u ${SVC_USER} >/dev/null 2>&1; then
  useradd --system --home-dir ${APP} --shell /usr/sbin/nologin ${SVC_USER}
fi
chown -R ${SVC_USER}:${SVC_USER} ${DATA}
chmod 700 ${DATA}
chmod 755 ${APP}
mkdir -p /var/www/acero-acme
chmod 755 /var/www/acero-acme

# ---------------------------------------------------------------- 4. service
echo "[4/7] Creating the service..."
cat > /etc/systemd/system/acero-rtdb.service <<SVCEOF
[Unit]
Description=ACERO REALTIME DB
After=network.target

[Service]
Environment=RTDB_BASE=${DATA}
ExecStart=/usr/bin/python3 ${APP}/panel.py serve
Restart=always
RestartSec=2
User=${SVC_USER}
Group=${SVC_USER}
LimitNOFILE=65535
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=true
ReadWritePaths=${DATA}

[Install]
WantedBy=multi-user.target
SVCEOF

cat > /usr/local/bin/acero-rtdb <<'WRAPEOF'
#!/usr/bin/env bash
# ACERO REALTIME DB helper
APP=/opt/acero-rtdb
DATA=$APP/data
case "${1:-}" in
  setpw)
    [[ ${#2} -ge 8 ]] || { echo "Usage: acero-rtdb setpw 'newpassword'   (8+ characters)"; exit 1; }
    runuser -u acerodb -- env PW="$2" RTDB_BASE=$DATA python3 $APP/panel.py setpw && systemctl restart acero-rtdb ;;
  info)    cat /root/acero-rtdb-info.txt ;;
  status)  systemctl status acero-rtdb nginx --no-pager ;;
  restart) systemctl restart acero-rtdb && echo restarted ;;
  logs)    journalctl -u acero-rtdb -f ;;
  backup)
    T=$(mktemp -d)
    python3 - "$T" <<'PY'
import sqlite3, sys
s = sqlite3.connect('/opt/acero-rtdb/data/rtdb.sqlite3')
d = sqlite3.connect(sys.argv[1] + '/rtdb.sqlite3')
s.backup(d)
d.close()
PY
    cp $DATA/config.json $DATA/secret.key "$T"/
    OUT=/root/acero-rtdb-backup-$(date +%Y%m%d-%H%M).tar.gz
    tar czf "$OUT" -C "$T" . && rm -rf "$T" && echo "Backup saved: $OUT" ;;
  restore)
    [[ -f "${2:-}" ]] || { echo "Usage: acero-rtdb restore /root/acero-rtdb-backup-XXXX.tar.gz"; exit 1; }
    systemctl stop acero-rtdb
    rm -f $DATA/rtdb.sqlite3 $DATA/rtdb.sqlite3-wal $DATA/rtdb.sqlite3-shm
    tar xzf "$2" -C $DATA && chown -R acerodb:acerodb $DATA && chmod 700 $DATA
    systemctl start acero-rtdb && echo "Restored." ;;
  *) echo "Usage: acero-rtdb {info|status|restart|logs|setpw 'newpassword'|backup|restore FILE.tar.gz}" ;;
esac
WRAPEOF
chmod 755 /usr/local/bin/acero-rtdb

systemctl daemon-reload
systemctl enable acero-rtdb >/dev/null 2>&1
systemctl restart acero-rtdb

# ---------------------------------------------------------------- 5. nginx + HTTPS
echo "[5/7] Configuring Nginx and HTTPS..."
# Switched between IP and domain (or to another domain)? The old certificate is for the old name: start over.
if [[ -f ${CERT_DIR}/host && "$(cat ${CERT_DIR}/host)" != "${HOST}" ]]; then
  rm -f ${CERT_DIR}/letsencrypt ${CERT_DIR}/panel.crt ${CERT_DIR}/panel.key
fi
echo "${HOST}" > ${CERT_DIR}/host
if [[ ! -f ${CERT_DIR}/panel.crt ]]; then
  openssl req -x509 -nodes -newkey rsa:2048 -days 3650 -keyout ${CERT_DIR}/panel.key -out ${CERT_DIR}/panel.crt \
    -subj "/CN=${HOST}" >/dev/null 2>&1
  chmod 600 ${CERT_DIR}/panel.key
fi

if [[ $HOST_IS_IP -eq 1 ]]; then SERVER_NAME="_"; D=" default_server"; else SERVER_NAME="${HOST}"; D=""; fi
LISTEN80="listen 80${D};"
LISTEN443="listen 443 ssl http2${D};"
if [[ -f /proc/net/if_inet6 ]]; then
  LISTEN80="${LISTEN80} listen [::]:80${D};"
  LISTEN443="${LISTEN443} listen [::]:443 ssl http2${D};"
fi

rm -f /etc/nginx/sites-enabled/default
cat > /etc/nginx/conf.d/acero-rtdb.conf <<NGXEOF
# ACERO REALTIME DB (made by install.sh; it is rewritten on every upgrade)
server {
    ${LISTEN80}
    server_name ${SERVER_NAME};
    server_tokens off;

    location ^~ /.well-known/acme-challenge/ {
        root /var/www/acero-acme;
        default_type text/plain;
    }
    location / {
        return 301 https://\$host\$request_uri;
    }
}

server {
    ${LISTEN443}
    server_name ${SERVER_NAME};
    server_tokens off;
    ssl_certificate ${CERT_DIR}/panel.crt;
    ssl_certificate_key ${CERT_DIR}/panel.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    client_max_body_size 8m;

    location = /${SECRET} {
        return 301 https://\$host/${SECRET}/panel/;
    }
    location = /${SECRET}/panel {
        return 301 https://\$host/${SECRET}/panel/;
    }

    # Panel
    location ^~ /${SECRET}/panel/ {
        proxy_pass http://127.0.0.1:${PANEL_PORT};
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host \$host;
        proxy_set_header X-Forwarded-For \$remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_read_timeout 120s;
    }

    # Database API, live streams (Server-Sent Events) and /sdk.js
    location / {
        proxy_pass http://127.0.0.1:${API_PORT};
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host \$host;
        proxy_set_header X-Forwarded-For \$remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_buffering off;
        proxy_cache off;
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
    }
}
NGXEOF

nginx -t
systemctl enable nginx >/dev/null 2>&1 || true
systemctl restart nginx

if command -v ufw >/dev/null 2>&1 && ufw status | grep -q "Status: active"; then
  ufw allow 80/tcp || true
  ufw allow 443/tcp || true
fi

# ---------------------------------------------------------------- 6. trusted certificate (Let's Encrypt)
echo "[6/7] Getting a trusted HTTPS certificate..."
CERT_NOTE="Self-signed certificate: browsers and websites will NOT trust it. See the guide (Kung may mali) to fix this."
issue_cert() {
  if [[ ! -x ${ACME_HOME}/acme.sh ]]; then
    curl -fsSL https://raw.githubusercontent.com/acmesh-official/acme.sh/master/acme.sh -o ${ACME_HOME}/acme.sh || return 1
    chmod 700 ${ACME_HOME}/acme.sh
  fi
  if [[ $HOST_IS_IP -eq 1 ]]; then
    ${ACME_HOME}/acme.sh --home ${ACME_HOME} --issue --server letsencrypt -d "${HOST}" \
      -w /var/www/acero-acme --certificate-profile shortlived --days 3 || return 1
  else
    ${ACME_HOME}/acme.sh --home ${ACME_HOME} --issue --server letsencrypt -d "${HOST}" \
      -w /var/www/acero-acme || return 1
  fi
  ${ACME_HOME}/acme.sh --home ${ACME_HOME} --install-cert -d "${HOST}" \
    --fullchain-file ${CERT_DIR}/panel.crt --key-file ${CERT_DIR}/panel.key \
    --reloadcmd "systemctl reload nginx" || return 1
  chmod 600 ${CERT_DIR}/panel.key
  touch ${CERT_DIR}/letsencrypt
}
if [[ -f ${CERT_DIR}/letsencrypt && -x ${ACME_HOME}/acme.sh ]]; then
  CERT_NOTE="Trusted Let's Encrypt certificate (auto-renews)."
elif issue_cert; then
  CERT_NOTE="Trusted Let's Encrypt certificate (auto-renews)."
else
  echo "Could not get a Let's Encrypt certificate. Check: port 80 open in your provider firewall, and for a domain, its A record points to ${IP}."
  echo "The install continues with a self-signed certificate. After fixing it, run this script again."
fi
if [[ -f ${CERT_DIR}/letsencrypt ]]; then
  cat > /etc/systemd/system/acero-cert-renew.service <<SVCEOF
[Unit]
Description=Renew ACERO REALTIME DB certificate

[Service]
Type=oneshot
ExecStart=${ACME_HOME}/acme.sh --cron --home ${ACME_HOME}
SVCEOF
  cat > /etc/systemd/system/acero-cert-renew.timer <<SVCEOF
[Unit]
Description=Check the ACERO REALTIME DB certificate twice a day

[Timer]
OnCalendar=*-*-* 03,15:17:00
RandomizedDelaySec=900
Persistent=true

[Install]
WantedBy=timers.target
SVCEOF
  systemctl daemon-reload
  systemctl enable --now acero-cert-renew.timer >/dev/null 2>&1 || true
fi

# ---------------------------------------------------------------- 7. check + info
echo "[7/7] Checking..."
OKH=0
for i in $(seq 1 20); do
  if curl -fsS http://127.0.0.1:${API_PORT}/health >/dev/null 2>&1; then OKH=1; break; fi
  sleep 1
done
if [[ $OKH -ne 1 ]]; then
  echo "The service did not start. Look at: journalctl -u acero-rtdb -n 40 --no-pager" >&2
  exit 1
fi

if [[ $UPGRADE -eq 1 ]]; then
  echo "Upgraded. Same panel URL and password as before:"
  echo "  ${PUBLIC_URL}/${SECRET}/panel/"
  echo "${CERT_NOTE}"
  exit 0
fi

cat > "$INFO" <<INFOEOF
Panel URL : ${PUBLIC_URL}/${SECRET}/panel/
Password  : ${PANEL_PW}
API base  : ${PUBLIC_URL}
SDK       : ${PUBLIC_URL}/sdk.js
Certificate: ${CERT_NOTE}

Open ports 80/tcp and 443/tcp in your VPS provider firewall.
Commands  : acero-rtdb info | status | restart | logs | setpw 'newpassword' | backup | restore FILE.tar.gz
Data      : ${DATA}
INFOEOF
chmod 600 "$INFO"
echo
echo "=========== DONE ==========="
cat "$INFO"
echo "============================"
echo "Saved to ${INFO}"
