#!/bin/bash

# ── Source .env — loads ALL variables (APP_PORT, etc.) into the environment ───
# Every process started from this script (scheduler, gunicorn, Python) will
# inherit these variables automatically via os.environ / $VAR — no per-file
# parsing needed anywhere else.
if [ -f "/website/.env" ]; then
    set -a
    source /website/.env
    set +a
fi

# Start the scheduler (expire files, overdue jobs, backup sync).
# Replaces the old RQ worker.py processes — do NOT start worker.py.
echo "Starting scheduler..."
nohup python3 /website/scheduler_runner.py > /website/logs/scheduler.log 2>&1 &

sleep 2

# ── First-boot: disable main admin 2FA to prevent Docker login conflicts ──────
# Runs once on first container start (sentinel file guards re-runs).
# Set DISABLE_ADMIN_2FA_ON_INIT=1 to force a reset on any restart.
SENTINEL="/website/storage/.2fa_init_cleared"
if [ ! -f "$SENTINEL" ] || [ "${DISABLE_ADMIN_2FA_ON_INIT:-0}" = "1" ]; then
    echo "First boot: clearing admin 2FA..."
    python3 - <<'PYEOF'
import sqlite3
try:
    with sqlite3.connect('/website/storage/sqlite.db') as conn:
        conn.execute("UPDATE admin_profiles SET totp_secret='', totp_enabled=0 WHERE id=(SELECT id FROM admin_profiles ORDER BY id LIMIT 1)")
        conn.commit()
    print("Admin 2FA cleared successfully.")
except Exception as e:
    print(f"Warning: could not clear admin 2FA: {e}")
PYEOF
    if [ "${DISABLE_ADMIN_2FA_ON_INIT:-0}" != "1" ]; then
        touch "$SENTINEL"
    fi
fi

# ── Re-apply domain replacement from DB on every boot ──────────────────────────
# Always replaces 'onlineconvert.cc' → new_domain (catches fresh Docker builds)
# AND brand_original_domain → new_domain (catches live containers already updated).
echo "Applying domain replacement from settings..."
python3 - <<'BRANDEOF'
import sqlite3, os, re

APP_DIR      = os.environ.get('APP_DIR', '/website')
HOST_APP_DIR = (os.environ.get('HOST_APP_DIR') or '').strip()
DB_PATH      = '/website/storage/sqlite.db'

def get_setting(conn, key):
    row = conn.execute("SELECT value FROM site_settings WHERE key=?", (key,)).fetchone()
    return row[0] if row else ''

def mirror_case(src, tgt):
    if not src or not tgt: return tgt
    if src.isupper(): return tgt.upper()
    if src.islower(): return tgt.lower()
    if src[0].isupper(): return tgt[0].upper() + tgt[1:]
    return tgt

def apply_pairs(base_dir, pairs):
    """Replace all pairs (old, new) in every .html file under base_dir/templates/."""
    if not pairs:
        return
    # Sort longest-first; case-insensitive
    ps = sorted(pairs, key=lambda x: -len(x[0]))
    lke = {o: r for o, r in ps}
    lkl = {o.lower(): r for o, r in ps}
    rx  = re.compile('|'.join(re.escape(o) for o, _ in ps), re.IGNORECASE)

    def _sub(m):
        s = m.group(0)
        if s in lke: return lke[s]
        return mirror_case(s, lkl.get(s.lower(), s))

    tpl_dir = os.path.join(base_dir, 'templates')
    if not os.path.isdir(tpl_dir):
        return
    changed = 0
    for root, dirs, files in os.walk(tpl_dir):
        dirs[:] = [d for d in dirs if d not in ['__pycache__', '.git']]
        for fn in files:
            if not fn.endswith(('.html', '.htm')):
                continue
            fp = os.path.join(root, fn)
            try:
                with open(fp, encoding='utf-8', errors='ignore') as f:
                    orig = f.read()
                cur = orig
                for _ in range(5):
                    nxt = rx.sub(_sub, cur)
                    if nxt == cur: break
                    cur = nxt
                if cur != orig:
                    with open(fp, 'w', encoding='utf-8') as f:
                        f.write(cur)
                    changed += 1
            except Exception:
                pass
    return changed

try:
    with sqlite3.connect(DB_PATH) as conn:
        new_domain    = get_setting(conn, 'brand_domain').strip()
        new_name      = get_setting(conn, 'brand_replacement').strip()
        stored_old    = get_setting(conn, 'brand_original_domain').strip()
        stored_oldname= get_setting(conn, 'brand_original_name').strip()

    if not new_domain:
        print("No domain replacement configured — skipping.")
    else:
        if not new_name:
            new_name = new_domain.split('.')[0].capitalize()
        old_name = stored_oldname or 'onlineconvert'

        # Build de-duplicated pair list:
        # 1. Always try the hardcoded original strings (fresh Docker build)
        # 2. Also try the stored previous domain (live container already updated)
        pairs = []
        seen = set()
        for od, nd in [('onlineconvert.cc', new_domain),
                       ('onlineconvert',    new_name),
                       (stored_old,         new_domain),
                       (old_name,           new_name)]:
            if od and nd and od.lower() != nd.lower() and od.lower() not in seen:
                pairs.append((od, nd))
                seen.add(od.lower())

        if pairs:
            n = apply_pairs(APP_DIR, pairs)
            print(f"Domain replacement applied ({len(pairs)} pairs, {n} files changed)")
            if HOST_APP_DIR and os.path.isdir(HOST_APP_DIR):
                apply_pairs(HOST_APP_DIR, pairs)
                print(f"Domain replacement applied to host dir: {HOST_APP_DIR}")
        else:
            print("Domain already matches target — no replacement needed.")
except Exception as e:
    print(f"Warning: domain replacement on boot failed: {e}")
BRANDEOF

# ── Regenerate sitemaps ──────────────────────────────────────────────────────
echo "Regenerating sitemaps..."
cd /website && python scripts/generate_sitemaps.py && echo "Sitemaps done." || echo "Warning: sitemap generation failed (non-fatal)."
cd /website

# APP_PORT is already in the environment from the .env source block at the top.
# Fall back to 6001 only if .env didn't set it.
export APP_PORT="${APP_PORT:-6001}"

# Start Gunicorn using gunicorn.conf.py.
# The config sets workers=2, gthread, threads=4 and includes the post_fork
# hook that re-spawns LocalQueue consumer threads after each worker forks.
echo "Starting Gunicorn on port ${APP_PORT}..."
exec gunicorn \
    --config /website/gunicorn.conf.py \
    --bind "0.0.0.0:${APP_PORT}" \
    wsgi:app
