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

IDLE_TIMEOUT="${IDLE_TIMEOUT:-1800}"
X11VNC_FLAGS="${X11VNC_FLAGS:--wait 5 -defer 5 -threads}"
SCREEN_GEOMETRY="${SCREEN_GEOMETRY:-1920x1080x24}"
CHROME_WINDOW_SIZE="${CHROME_WINDOW_SIZE:-1920,1080}"
ENABLE_HEARTBEAT="${ENABLE_HEARTBEAT:-1}"
DISPLAY_NUM="${DISPLAY_NUM:-:1}"

mkdir -p /opt/portal
cp -r /usr/share/novnc/* /opt/portal/

cat > /opt/portal/index.html <<'HTML'
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Universal Session</title>
  <style>
    html,body,#screen{margin:0;height:100%;background:#111}
    .status{
      position:fixed;
      left:12px;
      top:12px;
      z-index:50;
      padding:8px 10px;
      border-radius:8px;
      background:rgba(16,22,32,.86);
      border:1px solid rgba(255,255,255,.18);
      color:#dce8f5;
      font:600 13px/1.25 sans-serif;
      max-width:min(92vw,560px);
    }
    .status.error{
      background:rgba(85,20,20,.9);
      border-color:rgba(255,130,130,.36);
      color:#ffe3e3;
    }
    .status.hidden{display:none}
    .nav-panel{
      position:fixed;left:16px;top:64px;z-index:99;display:flex;gap:10px;
      background:linear-gradient(180deg,rgba(15,24,36,.78),rgba(9,14,22,.86));border:1px solid rgba(255,255,255,.22);backdrop-filter: blur(5px);
      box-shadow:0 10px 28px rgba(0,0,0,.36);padding:9px 10px;border-radius:14px;
      cursor:grab;user-select:none;touch-action:none
    }
    .nav-btn{
      border:1px solid rgba(255,255,255,.26);border-radius:999px;padding:9px 14px;cursor:pointer;letter-spacing:.01em;
      background:linear-gradient(180deg,#2a8cd6,#1668a6);color:#fff;font:700 13px/1 sans-serif;box-shadow:inset 0 1px 0 rgba(255,255,255,.22),0 5px 12px rgba(10,46,78,.45)
    }
    .nav-btn:hover{filter:brightness(1.08)}
    .nav-btn:active{transform:translateY(1px)}
    .nav-panel.dragging{cursor:grabbing;opacity:.85}
  </style>
</head>
<body>
  <div id="screen"></div>
  <div id="status" class="status">Подключение к слоту...</div>
  <div class="nav-panel">
    <button class="nav-btn" id="btn-back" type="button" title="Назад">←</button>
    <button class="nav-btn" id="btn-home" type="button" title="Главная">⌂</button>
    <button class="nav-btn" id="btn-fs" type="button" title="На весь экран">⛶</button>
  </div>
  <script type="module">
    import RFB from './core/rfb.js';
    const basePath = location.pathname.replace(/\/+$/, '');
    const wsUrl = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + basePath + '/websockify';
    const statusEl = document.getElementById('status');
    const XK_ALT_L = 0xffe9;
    const XK_LEFT = 0xff51;

    let rfb = null;
    let connected = false;
    let connectTimer = null;
    let reconnectTimer = null;
    let reconnectAttempts = 0;
    const MAX_RECONNECT_ATTEMPTS = 12;
    const RECONNECT_DELAYS_MS = [1000, 2000, 3000, 5000, 8000];
    let manualDisconnect = false;

    function showStatus(text, isError = false) {
      statusEl.textContent = text;
      statusEl.classList.toggle('error', !!isError);
      statusEl.classList.remove('hidden');
    }

    function hideStatus() {
      statusEl.classList.add('hidden');
    }

    function clearConnectTimer() {
      if (connectTimer) {
        clearTimeout(connectTimer);
        connectTimer = null;
      }
    }

    function clearReconnectTimer() {
      if (reconnectTimer) {
        clearTimeout(reconnectTimer);
        reconnectTimer = null;
      }
    }

    function reconnectDelay(attemptNumber) {
      const idx = Math.min(Math.max(attemptNumber - 1, 0), RECONNECT_DELAYS_MS.length - 1);
      return RECONNECT_DELAYS_MS[idx];
    }

    function scheduleConnectTimeout() {
      clearConnectTimer();
      connectTimer = setTimeout(() => {
        if (!connected && !manualDisconnect) {
          scheduleReconnect('Нет подключения к экрану слота. Пробуем переподключиться...');
        }
      }, 8000);
    }

    function scheduleReconnect(reasonText) {
      if (manualDisconnect) return;
      clearConnectTimer();
      clearReconnectTimer();

      if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
        showStatus('Соединение со слотом потеряно. Переподключение не удалось. Откройте сервис заново.', true);
        return;
      }

      const nextAttempt = reconnectAttempts + 1;
      const delayMs = reconnectDelay(nextAttempt);
      const delaySec = Math.ceil(delayMs / 1000);
      showStatus(`${reasonText} Повтор ${nextAttempt}/${MAX_RECONNECT_ATTEMPTS} через ${delaySec} сек.`, true);

      reconnectTimer = setTimeout(() => {
        reconnectAttempts = nextAttempt;
        connectRfb('Переподключение к слоту...');
      }, delayMs);
    }

    function attachRfb() {
      if (rfb) {
        try { rfb.disconnect(); } catch (e) {}
      }
      rfb = new RFB(document.getElementById('screen'), wsUrl);
      rfb.viewOnly = false;
      rfb.scaleViewport = true;
      rfb.resizeSession = true;

      rfb.addEventListener('connect', () => {
        connected = true;
        reconnectAttempts = 0;
        clearConnectTimer();
        clearReconnectTimer();
        hideStatus();
      });

      rfb.addEventListener('disconnect', () => {
        connected = false;
        if (manualDisconnect) return;
        scheduleReconnect('Соединение со слотом потеряно.');
      });
    }

    function connectRfb(statusText) {
      if (manualDisconnect) return;
      connected = false;
      showStatus(statusText || 'Подключение к слоту...');
      attachRfb();
      scheduleConnectTimeout();
    }

    const enableHeartbeat = (new URLSearchParams(location.search).get('hb') ?? '1') !== '0';
    const sid = new URLSearchParams(location.search).get('sid');
    const SESSION_CLOSED_URL_BASE = '/?session_closed=';
    const CLOSE_PATH = sid ? `/api/sessions/${sid}/close` : '';

    function goSessionClosed(reason = 'idle') {
      const safeReason = reason === 'limit' ? 'limit' : 'idle';
      const target = `${SESSION_CLOSED_URL_BASE}${safeReason}`;
      try {
        if (window.top && window.top !== window) {
          window.top.location.href = target;
          return;
        }
      } catch (e) {}
      window.location.href = target;
    }

    async function touch() {
      if (!sid) return;
      try {
        const res = await fetch(`/api/sessions/${sid}/touch`, {method:'POST', credentials:'include'});
        if (!res.ok) {
          let reason = 'idle';
          try {
            const payload = await res.json();
            if (payload && typeof payload.reason === 'string') {
              reason = payload.reason;
            }
          } catch (e) {}
          goSessionClosed(reason);
        }
      } catch (e) {}
    }

    let closing = false;
    async function closeSessionNow() {
      if (!CLOSE_PATH || closing) return;
      closing = true;
      manualDisconnect = true;
      clearConnectTimer();
      clearReconnectTimer();
      try {
        if (rfb) rfb.disconnect();
      } catch (e) {}
      try {
        await fetch(CLOSE_PATH, {method: 'POST', credentials: 'include', keepalive: true});
      } catch (e) {}
    }

    if (enableHeartbeat) {
      setInterval(touch, 15000);
      touch();
      window.addEventListener('pagehide', closeSessionNow);
      window.addEventListener('beforeunload', closeSessionNow);
    }

    function keyTap(keysym, code) {
      if (!rfb) return;
      rfb.sendKey(keysym, code, true);
      rfb.sendKey(keysym, code, false);
    }

    function chord(mod, key, modCode, keyCode) {
      if (!rfb) return;
      rfb.sendKey(mod, modCode, true);
      keyTap(key, keyCode);
      rfb.sendKey(mod, modCode, false);
    }

    function goHome() {
      manualDisconnect = true;
      clearConnectTimer();
      clearReconnectTimer();
      try {
        if (window.top && window.top !== window) {
          window.top.location.href = '/';
          return;
        }
      } catch (e) {}
      window.location.href = '/';
    }

    document.getElementById('btn-back').addEventListener('click', () => chord(XK_ALT_L, XK_LEFT, 'AltLeft', 'ArrowLeft'));
    document.getElementById('btn-home').addEventListener('click', goHome);
    document.getElementById('btn-fs').addEventListener('click', () => {
      if (!document.fullscreenElement) document.documentElement.requestFullscreen();
      else document.exitFullscreen();
    });
    document.addEventListener('fullscreenchange', () => {
      document.getElementById('btn-fs').textContent = document.fullscreenElement ? '✕' : '⛶';
      document.getElementById('btn-fs').title = document.fullscreenElement ? 'Выйти из полного экрана' : 'На весь экран';
    });
    document.addEventListener('contextmenu', (e) => e.preventDefault());

    (function(){
      const p = document.querySelector('.nav-panel');
      const SK = 'portal_nav_pos';
      try { const s = JSON.parse(localStorage.getItem(SK)); if(s){p.style.left=s.x+'px';p.style.top=s.y+'px';} } catch(e){}
      let ox, oy, dragged = false;
      p.addEventListener('pointerdown', e => {
        if (e.target.closest('button')) return;
        dragged = false;
        ox = e.clientX - p.getBoundingClientRect().left;
        oy = e.clientY - p.getBoundingClientRect().top;
        p.setPointerCapture(e.pointerId);
        p.classList.add('dragging');
      });
      p.addEventListener('pointermove', e => {
        if (!p.hasPointerCapture(e.pointerId)) return;
        dragged = true;
        const x = Math.max(0, Math.min(window.innerWidth - p.offsetWidth, e.clientX - ox));
        const y = Math.max(0, Math.min(window.innerHeight - p.offsetHeight, e.clientY - oy));
        p.style.left = x + 'px';
        p.style.top = y + 'px';
      });
      p.addEventListener('pointerup', () => {
        p.classList.remove('dragging');
        if (dragged) try { localStorage.setItem(SK, JSON.stringify({x: parseInt(p.style.left), y: parseInt(p.style.top)})); } catch(e){}
      });
    })();

    connectRfb('Подключение к слоту...');
  </script>
</body>
</html>
HTML

export DISPLAY="$DISPLAY_NUM"
export CHROME_WINDOW_SIZE
Xvfb "$DISPLAY_NUM" -screen 0 "$SCREEN_GEOMETRY" >/tmp/xvfb.log 2>&1 &
fluxbox >/tmp/fluxbox.log 2>&1 &
python3 /manager.py >/tmp/manager.log 2>&1 &
start_x11vnc_with_retry() {
  local display_arg="$1"
  local attempt=0
  while [ "$attempt" -lt 12 ]; do
    x11vnc -display "$display_arg" -rfbport 5900 -forever -shared -nopw -noxdamage $X11VNC_FLAGS >/tmp/x11vnc.log 2>&1 &
    local pid=$!
    sleep 1
    if kill -0 "$pid" 2>/dev/null; then
      return 0
    fi
    attempt=$((attempt + 1))
    sleep 0.5
  done
  return 1
}

start_x11vnc_with_retry "$DISPLAY_NUM" || true

exec websockify --verbose --idle-timeout="$IDLE_TIMEOUT" --web=/opt/portal 6080 localhost:5900
