#!/usr/bin/python3 -I
"""Fixed privileged endpoint for the two-field live installer."""
import fcntl
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import syslog
import time

HERE=Path(__file__).resolve().parent
sys.path.insert(0,str(HERE))
from quick import STATE,accept,disk,is_live,debug_mode


def runtime_config():
    config=STATE/'calamares'
    config.mkdir(exist_ok=True,mode=0o755)
    mods=config/'modules'
    mods.mkdir(exist_ok=True,mode=0o755)
    for item in Path('/etc/calamares/modules').iterdir():
        dest=mods/item.name
        if not dest.exists() and not dest.is_symlink():dest.symlink_to(item)
    qml=config/'qml'
    if not qml.exists():qml.symlink_to('/usr/share/calamares/qml')
    bootconfig=mods/'nw-bootloader.conf'
    if not bootconfig.exists():bootconfig.symlink_to('/etc/calamares/modules/bootloader.conf')
    branding=config/'branding'
    if not branding.exists():branding.symlink_to('/etc/calamares/branding')
    shutil.copyfile('/etc/newworld-installer/settings.conf',config/'settings.conf')
    # Upstream unpackfs reports real copy progress weighted by unpack entry.
    (mods/'nw-unpack.conf').write_text('unpack:\n  - source: /run/live/medium/live/filesystem.squashfs\n    sourcefs: squashfs\n    destination: ""\n    weight: 99\n  - source: /run/live/medium/live/zz-compact.squashfs\n    sourcefs: squashfs\n    destination: ""\n    weight: 1\n')
    return config


def usb_log(*command):
    try:
        subprocess.run(['/usr/lib/newworld-installer/usb-log',*command],timeout=60,check=True,
                       stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    except (OSError,subprocess.SubprocessError):
        print('The installation USB log could not be updated.',file=sys.stderr)


def fail(message):
    from progress import emit
    # Preserve the stage already reported by the last successful job.
    stage='prepare'
    try:
        for line in (STATE/'events.jsonl').read_text().splitlines():
            stage=json.loads(line).get('stage') or stage
    except (OSError,ValueError):pass
    emit(stage,status='error',detail=message)
    usb_log('finish','failed')


def prepare_request():
    from progress import emit
    request=json.loads(sys.stdin.buffer.readline(2049))
    accept(request)
    config=runtime_config()
    with open(STATE/'request.json','w',opener=lambda p,f:os.open(p,f,0o600)) as out:json.dump(request,out)
    (STATE/'complete').unlink(missing_ok=True)
    pending=STATE/'events.next'
    with pending.open('w') as journal:os.fchmod(journal.fileno(),0o644)
    pending.replace(STATE/'events.jsonl')
    usb_log('retry')
    emit('prepare',fraction=0)
    return request,config


def run_job():
    from progress import emit
    try:
        request,config=prepare_request()
    except Exception as error:
        # No install has started. A stale or invalid form must not close the
        # current USB log or emit a terminal event for a later valid request.
        syslog.syslog(syslog.LOG_WARNING,'NewWorld setup request was not started ('+type(error).__name__+').')
        return 2
    print('READY',flush=True)
    env={**os.environ,'QT_QPA_PLATFORM':'offscreen','QT_QUICK_BACKEND':'software','QT_OPENGL':'software',
         'XDG_RUNTIME_DIR':'/run/newworld-installer/qt-runtime','LANG':'he_IL.UTF-8' if request['lang']=='he' else 'en_US.UTF-8',
         'HOME':'/root','LC_ALL':'C.UTF-8'}
    Path(env['XDG_RUNTIME_DIR']).mkdir(mode=0o700,exist_ok=True)
    # A missing stock configuration or module must fail before the first disk job.
    for tool in ('sfdisk','udevadm','blkid','mkfs.vfat','mkfs.ext4','chroot','calamares'):
        if not shutil.which(tool):raise RuntimeError('A required installer tool is missing.')
    emit('prepare',fraction=1)
    start=time.monotonic();problem=False
    with open(STATE/'install.log','w',opener=lambda p,f:os.open(p,f,0o600)) as log:
        proc=subprocess.Popen(['/usr/bin/calamares','-c',str(config)],env=env,stdout=log,stderr=log)
        try:
            with (STATE/'install.log').open(errors='replace') as tail:
                while proc.poll() is None:
                    lines=tail.readlines()
                    if any(('Installation failed:' in line or 'failed modules' in line.lower() or 'FATAL:' in line) for line in lines):
                        problem=True
                        break
                    if (STATE/'complete').is_file():break
                    if time.monotonic()-start>180 and not (STATE/'job-started').exists():
                        problem=True
                        break
                    time.sleep(.4)
        finally:
            if proc.poll() is None:
                proc.terminate()
                try:proc.wait(8)
                except subprocess.TimeoutExpired:proc.kill();proc.wait()
    if problem or not (STATE/'complete').is_file():
        fail('Installation stopped. The disk has not been marked complete.')
        return 1
    emit('finalize',fraction=1,status='success')
    usb_log('finish','ok')
    time.sleep(30)
    subprocess.run(['systemctl','reboot','--no-block'],check=True)
    return 0


def main():
    if os.geteuid()!=0 or debug_mode() or not is_live():
        return 2
    if sys.argv[1:]==['--inspect']:
        print(json.dumps(disk('inspect')));return 0
    if len(sys.argv)!=1:return 2
    STATE.mkdir(mode=0o755,exist_ok=True)
    with (STATE/'lock').open('a') as lock:
        try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        except BlockingIOError:return 3
        (STATE/'job-started').unlink(missing_ok=True)
        try:return run_job()
        except Exception:
            fail('Installation could not start or complete.');return 1


if __name__=='__main__':sys.exit(main())
