#!/usr/bin/python3 -E
"""Install all pinned Craft Apps after user consent. Can resume a partially completed run."""
import fcntl
import hashlib
import os
from pathlib import Path, PurePosixPath
import shutil
import stat
import subprocess
import sys
import tempfile
from urllib.parse import urlsplit
from zipfile import BadZipFile, ZipFile

from artcraft import architecture, catalog, desktop, installed_native, installed_web, web_index

CACHE = Path('/var/cache/newworld-artcraft')
BUNDLED = Path('/usr/local/share/newworld-artcraft')
OFFLINE = (BUNDLED, Path('/run/live/medium/newworld-artcraft'), Path('/mnt/artcraft'))
APT = ['/usr/bin/apt-get', '-o', 'DPkg::Lock::Timeout=120', '-y', '--no-remove',
       '--no-install-recommends', 'install']


def progress(kind, name, **values):
    if os.environ.get('NEWWORLD_APP_PROGRESS') == '1':
        # The amd64 provisioning package owns the optional reporting protocol.
        # Standalone native and i386 installs need only their existing dependencies.
        helper = '/usr/local/lib/compact-apps'
        if helper not in sys.path: sys.path.insert(0, helper)
        try: from app_progress import emit_event
        except ImportError: return
        emit_event(kind, name, **values)


def good(path, asset):
    if not path.is_file() or path.stat().st_size != asset['size']:
        return False
    digest = hashlib.sha256()
    with path.open('rb') as src:
        for piece in iter(lambda: src.read(1024 * 1024), b''):
            digest.update(piece)
    return digest.hexdigest() == asset['sha256']


def fetch(asset):
    # All filenames and digests come from the image's root-owned, immutable release manifest.
    url = asset.get('url') or ''
    name = asset.get('filename') or Path(urlsplit(url).path).name
    if not name or Path(name).name != name:
        raise ValueError('Invalid asset name')
    target = CACHE/name
    if good(target, asset):
        return target
    part = CACHE/(name+'.partial')
    for folder in OFFLINE:
        origin = folder/name
        if origin.is_file():
            shutil.copyfile(origin, part)
            if good(part, asset):
                os.replace(part, target)
                return target
            part.unlink(missing_ok=True)
    if urlsplit(url).scheme != 'https' or urlsplit(url).hostname != 'github.com':
        raise ValueError('Expected bundled artifact is unavailable: '+name)
    curl = ['/usr/bin/curl','-q','--fail','--location','--proto','=https','--proto-redir','=https',
            '--silent','--show-error','--retry','3','--connect-timeout','20','--max-time','1200','--output',str(part)]
    for attempt in range(2):
        resume = ['--continue-at','-'] if part.is_file() and 0 < part.stat().st_size < asset['size'] else []
        completed = subprocess.run(curl + resume + [url])
        if good(part, asset):
            os.replace(part, target)
            return target
        if attempt == 0 and (completed.returncode in (0, 33, 36, 416) or (part.exists() and part.stat().st_size >= asset['size'])):
            part.unlink(missing_ok=True)
    raise RuntimeError('Download or SHA-256 verification failed: '+name)


def install_native(app):
    if installed_native(app) and desktop(app):
        return
    info = app['native']
    filename = info.get('filename') or Path(urlsplit(info['url']).path).name
    progress('transfer', app['name'], size=info['size'], path=str(CACHE/(filename+'.partial')))
    asset = fetch(info)
    # Package identity and architecture are checked in addition to the official release digest.
    for field, expected in [('Package', app['package']), ('Version', app['deb_version']), ('Architecture', 'amd64')]:
        value = subprocess.check_output(['/usr/bin/dpkg-deb','-f',str(asset),field],text=True).strip()
        if value != expected:
            raise ValueError('Unexpected Debian '+field+' for '+app['slug'])
    progress('verified', app['name'])
    apt = APT
    if os.environ.get('NEWWORLD_APP_PROGRESS') == '1':
        apt = [APT[0], '-o', 'APT::Status-Fd=1', *APT[1:]]
    subprocess.run(apt + [str(asset)], check=True,
                   env={**os.environ, 'DEBIAN_FRONTEND':'noninteractive'})
    if not installed_native(app) or not desktop(app):
        raise RuntimeError('Installed package or desktop entry could not be verified')
    asset.unlink(missing_ok=True)


def unpack_web(archive, stage, info):
    prefix = PurePosixPath(info['index']).parent
    with ZipFile(archive) as z:
        if sum(i.file_size for i in z.infolist()) != info['expanded_bytes']:
            raise ValueError('Unpacked file inventory mismatch')
        for item in z.infolist():
            path = PurePosixPath(item.filename)
            if path.is_absolute() or '..' in path.parts or stat.S_ISLNK(item.external_attr >> 16):
                raise ValueError('Unexpected archive entry')
            if not path.is_relative_to(prefix) or item.is_dir():
                continue
            dest = stage.joinpath(*path.relative_to(prefix).parts)
            dest.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
            with z.open(item) as source, dest.open('xb') as sink:
                shutil.copyfileobj(source, sink, length=1024*1024)
    if not (stage/'index.html').is_file() or not next(stage.rglob('*.wasm'), None):
        raise ValueError('Incomplete browser build')
    (stage/'.newworld-sha256').write_text(info['sha256']+'\n')


def web_launcher(app):
    slug, name = app['slug'],app['name']
    dst = Path('/usr/share/applications')/('newworld-web-'+slug+'.desktop')
    content = ('[Desktop Entry]\nType=Application\nName='+name+' (Web)\nName[he]='+name+
               ' (בדפדפן)\nExec=/usr/bin/newworld-artcraft --open '+slug+
               '\nIcon=applications-graphics\nCategories=Graphics;\nTerminal=false\n')
    tmp=dst.with_suffix('.tmp')
    tmp.write_text(content)
    os.replace(tmp,dst)


def install_web(app):
    if installed_web(app):
        web_launcher(app)
        return
    if not app.get('web'):
        raise RuntimeError('No verified browser artifact for '+app['name'])
    archive = fetch(app['web'])
    dest = web_index(app).parent
    dest.parent.mkdir(parents=True, exist_ok=True)
    stage = Path(tempfile.mkdtemp(dir=dest.parent, prefix='.install-'))
    try:
        stage.chmod(0o755)
        unpack_web(archive, stage, app['web'])
        # Only an incomplete legacy directory can occupy this exact immutable version.
        # Keep it until the staged replacement is ready, then recover on any rename failure.
        old=dest.with_name('.previous-'+app['version'])
        if old.exists() and not dest.exists():
            old.rename(dest)
        if old.exists():
            shutil.rmtree(old)
        if dest.exists():
            dest.rename(old)
        try:
            stage.rename(dest)
        except OSError:
            if old.exists():
                old.rename(dest)
            raise
        if old.exists():
            shutil.rmtree(old)
        web_launcher(app)
        archive.unlink(missing_ok=True)
    finally:
        if stage.exists():
            shutil.rmtree(stage)


def main():
    if os.geteuid() != 0 or len(sys.argv) != 1:
        return 2
    arch = architecture()
    if arch not in ('amd64','i386'):
        return 2
    os.umask(0o022)
    CACHE.mkdir(parents=True,exist_ok=True)
    with (CACHE/'.lock').open('a') as lock:
        fcntl.flock(lock,fcntl.LOCK_EX)
        failures = []
        apps = catalog()
        for i, app in enumerate(apps, 1):
            print(f"[{i}/{len(apps)}] {app['name']}",flush=True)
            progress('start', app['name'])
            try:
                (install_native if arch=='amd64' else install_web)(app)
                progress('done', app['name'])
            except (OSError, ValueError, RuntimeError, subprocess.SubprocessError, BadZipFile) as exc:
                progress('failed', app['name'])
                failures.append(app['name'])
                print(str(exc),file=sys.stderr,flush=True)
        if failures:
            print('Pending: '+', '.join(failures),file=sys.stderr)
            return 1
    return 0


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