"""Local RomM 5.4.0 adaptation. License: AGPL-3.0-only, as RomM.

The original frontend is pinned by its base-image digest. Fail closed if its
expected kiosk-device registration code changes. No authorization rules change.
"""
import gzip
import shutil
from pathlib import Path

root = Path("/var/www/html")
old = 'let e=s.user?.id;if(e!=null)try{T.value=await qe(e)??void 0}catch(e){console.error(`Registering this browser as a sync device failed`,e)}'
new = old.replace("if(e!=null)", "if(e!=null&&e>0)")
matches = [(file, file.read_text()) for file in (root / "assets").glob("Player-*.js") if old in file.read_text()]
assert len(matches) == 1, "Pinned RomM player changed; review the kiosk device guard"
file, text = matches[0]
assert text.count(old) == 1
text = text.replace(old, new)
file.write_text(text)
file.with_name(file.name + ".gz").write_bytes(gzip.compress(text.encode(), mtime=0))

index = root / "index.html"
html = index.read_text()
assert "</head>" in html and "</body>" in html
html = html.replace("</head>", '<link rel="stylesheet" href="/assets/harbor-arcade.css"><link rel="source" href="/harbor-source/"></head>', 1)
html = html.replace("</body>", '<a class="harbor-source-link" href="/harbor-source/">О сайте</a></body>', 1)
index.write_text(html)
index.with_name("index.html.gz").write_bytes(gzip.compress(html.encode(), mtime=0))

template = Path('/etc/nginx/templates/default.conf.template')
nginx = template.read_text()
assert nginx.count('    location / {') == 1, 'Pinned Nginx template changed'
nginx = nginx.replace('    location / {', '''    # Harbor's public library; RomM routes and player stay on their own entry.
    location = / {
        try_files /harbor-home.html =404;
        add_header Cache-Control "no-cache";
    }

    location / {''', 1)
template.write_text(nginx)

source = root / "harbor-source"
source.mkdir(exist_ok=True)
shutil.copyfile(__file__, source / "patch_romm.py")
shutil.copyfile(root / "assets/harbor-arcade.css", source / "harbor-arcade.css")
for name in ('harbor-home.css', 'harbor-home.js'):
    shutil.copyfile(root / 'assets' / name, source / name)
shutil.copyfile(root / 'harbor-home.html', source / 'home.html')
shutil.copyfile(template, source / 'nginx.template')
(source / "index.html").write_text('''<!doctype html><html lang="ru"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Harbor Arcade — о сайте</title><style>body{max-width:760px;margin:40px auto;padding:0 20px;background:#0f172a;color:#f8fafc;font:17px/1.6 "Segoe UI",sans-serif}a{color:#86efac}code{overflow-wrap:anywhere}</style><h1>Harbor Arcade</h1><p>Игровой каталог на базе RomM 5.4.0. Игры выполняются в браузере посетителя.</p><p><a href="/">Вернуться в библиотеку</a></p><h2>Исходный код</h2><p>RomM распространяется по лицензии AGPL-3.0. Локальные изменения: оформление и проверка, предотвращающая регистрацию анонимного гостя как устройства сохранений.</p><ul><li><a href="https://github.com/rommapp/romm/tree/5.4.0">Полный исходный код RomM 5.4.0</a></li><li><a href="Dockerfile">Dockerfile локальной сборки</a></li><li><a href="patch_romm.py">Изменения загрузочной страницы и гостевого игрока</a></li><li><a href="harbor-arcade.css">Исходник темы Harbor Arcade</a></li></ul><p>В исходном Player.vue локальная правка эквивалентна замене <code>if (userId == null) return;</code> на <code>if (userId == null || userId &lt;= 0) return;</code> перед вызовом browserDeviceId. Разрешения на сервере сохраняются.</p><p>Рекомендации оформления: <a href="https://github.com/nextlevelbuilder/ui-ux-pro-max-skill/tree/7246805992a42b7bba37d4cac83b01416f0c6c44">UI UX Pro Max</a>.</p></html>''')
source_index = source / 'index.html'
source_html = source_index.read_text().replace('</ul>', '<li><a href="home.html">Главная страница</a></li><li><a href="harbor-home.css">Оформление главной страницы</a></li><li><a href="harbor-home.js">Загрузка настоящей библиотеки</a></li><li><a href="nginx.template">Шаблон маршрутизации</a></li></ul>', 1)
source_index.write_text(source_html)
print("Harbor cinematic library installed; anonymous device registration guarded in", file.name)
