#!/usr/bin/python3
"""Kenbi launcher: isolated profile and desktop identity; no network setup."""
import json
import os
import shutil
import sys
import tempfile
from pathlib import Path

ROOT = Path('/opt/kenbi-web-browser')

def atomic_write(path, content, mode=0o600):
    handle, tmp = tempfile.mkstemp(prefix='.kenbi-', dir=path.parent)
    try:
        with os.fdopen(handle, 'wb') as stream:
            stream.write(content)
        os.chmod(tmp, mode)
        os.replace(tmp, path)
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)

def main():
    home = Path.home()
    xdg = os.environ.get('XDG_DATA_HOME', '')
    data = Path(xdg) if xdg and Path(xdg).is_absolute() else home / '.local/share'
    profile = data / 'kenbi-web-browser/profile'
    profile.mkdir(parents=True, exist_ok=True, mode=0o700)
    chrome = profile / 'chrome'
    chrome.mkdir(exist_ok=True, mode=0o700)
    config = profile / 'user.js'
    if not config.exists():
        defaults = (ROOT / 'assets/user.js').read_bytes()
        url = (ROOT / 'assets/start.html').as_uri()
        defaults += ('\nuser_pref("browser.startup.homepage", ' + json.dumps(url) + ');\n').encode()
        # Exclusive creation prevents a second first-launch from overwriting settings.
        try:
            with config.open('xb') as stream:
                os.chmod(config, 0o600)
                stream.write(defaults)
        except FileExistsError:
            pass
    atomic_write(chrome / 'userChrome.css', (ROOT / 'assets/userChrome.css').read_bytes())
    env = os.environ.copy()
    env['MOZ_APP_REMOTINGNAME'] = 'kenbi-web-browser'
    args = [str(ROOT / 'runtime/firefox'), '--name', 'kenbi-web-browser',
            '--class', 'kenbi-web-browser', '--profile', str(profile)] + sys.argv[1:]
    os.execve(args[0], args, env)

if __name__ == '__main__':
    try:
        main()
    except OSError as error:
        print('Kenbi Web Browser: no se pudo abrir el navegador: ' + str(error), file=sys.stderr)
        sys.exit(1)
