#!/usr/bin/env python3
# Generated by the Maskeno verified release build.
"""Maskeno's verified per-user Linux installer. Generated values are public."""
import argparse
import base64
import ctypes
import hashlib
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.request
from pathlib import Path

VERSION = "1.0.7"
PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAwLd6dPxsPOOmEhym0TWH0gVWdO3IREcCGkTYGcGSfP0=\n-----END PUBLIC KEY-----\n"
FEED = "https://downloads.maskeno.app/desktop/"


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def fetch_file(name, destination, maximum, source):
    if source:
        with (source / name).open('rb') as reader, destination.open('wb') as writer:
            copy_bounded(reader, writer, maximum)
        return
    request = urllib.request.Request(FEED + name, headers={'User-Agent': 'Maskeno-Linux-Installer/' + VERSION})
    with urllib.request.build_opener(NoRedirect).open(request, timeout=60) as reader, destination.open('wb') as writer:
        if reader.status != 200:
            raise RuntimeError('The download server did not return a file.')
        copy_bounded(reader, writer, maximum)


def copy_bounded(reader, writer, maximum):
    total = 0
    while True:
        chunk = reader.read(1024 * 1024)
        if not chunk:
            return
        total += len(chunk)
        if total > maximum:
            raise RuntimeError('The downloaded file is larger than the signed release permits.')
        writer.write(chunk)


def configure_runtime(target, work):
    try:
        ctypes.CDLL('libfuse.so.2')
    except OSError:
        distro = {}
        for line in Path('/etc/os-release').read_text().splitlines():
            if '=' in line:
                key, value = line.split('=', 1)
                distro[key] = value.strip('"')
        if distro.get('ID') != 'ubuntu' or not shutil.which('apt-get'):
            raise RuntimeError('Install the FUSE 2 runtime for your distribution, then run this installer again.')
        package = 'libfuse2t64' if int(distro.get('VERSION_ID', '0').split('.')[0]) >= 24 else 'libfuse2'
        print('Installing the FUSE runtime needed by AppImage. Administrator permission is required.')
        subprocess.run(['sudo', 'apt-get', 'update'], check=True)
        subprocess.run(['sudo', 'apt-get', 'install', '-y', '--no-install-recommends', package], check=True)
    restriction = Path('/proc/sys/kernel/apparmor_restrict_unprivileged_userns')
    if not restriction.exists() or restriction.read_text().strip() != '1':
        return
    path = str(target.resolve())
    if any(c in path for c in '\n\r\\"*?[]{}^$`%'):
        raise RuntimeError('This installation path cannot be represented safely in the application security profile.')
    name = 'maskeno_appimage_' + str(os.getuid())
    text = 'abi <abi/4.0>,\ninclude <tunables/global>\nprofile ' + name + ' "' + path + '" flags=(unconfined) {\n  userns,\n}\n'
    installed = Path('/etc/apparmor.d/maskeno-appimage-' + str(os.getuid()))
    if installed.exists() and installed.stat().st_uid == 0 and not (installed.stat().st_mode & 0o022) and installed.read_text() == text:
        return
    parser = shutil.which('apparmor_parser')
    if not parser:
        raise RuntimeError('AppArmor tools are required to permit this AppImage to use its Chromium sandbox.')
    profile = work / 'apparmor-profile'
    profile.write_text(text)
    print('Installing a security profile for this Maskeno path. Global namespace restrictions stay enabled.')
    subprocess.run(['sudo', 'install', '-m', '644', str(profile), str(installed)], check=True)
    subprocess.run(['sudo', parser, '-r', str(installed)], check=True)


def main():
    parser = argparse.ArgumentParser(description='Verify and install Maskeno ' + VERSION)
    parser.add_argument('--source-dir', type=Path, help='Use an offline copy of the signed release files')
    parser.add_argument('--verify-only', action='store_true', help='Verify the release without installing or changing system settings')
    parser.add_argument('--replace', action='store_true', help='Replace the existing application file with this verified version; project data is preserved')
    args = parser.parse_args()
    if sys.platform != 'linux' or platform.machine().lower() not in ('x86_64', 'amd64'):
        raise RuntimeError('This installer requires Linux x86_64.')
    if os.getuid() == 0 and not args.verify_only:
        raise RuntimeError('Run this installer as your desktop user. It asks for administrator permission only for system integration.')
    if not shutil.which('openssl'):
        raise RuntimeError('OpenSSL with Ed25519 support is required.')
    target = Path.home() / 'Applications' / 'Maskeno.AppImage'
    if not args.verify_only and target.is_symlink():
        raise RuntimeError('The existing application path is a symbolic link. Choose its real installation or remove the link explicitly before installing.')
    if not args.verify_only and target.exists() and not args.replace:
        raise RuntimeError('Maskeno is already installed. Use its update checker, or add --replace to install this version.')
    with tempfile.TemporaryDirectory(prefix='maskeno-install-') as temporary:
        work = Path(temporary)
        name = 'platform-release-' + VERSION + '.json'
        payload, signature = work / name, work / 'signature.base64'
        fetch_file(name, payload, 65536, args.source_dir)
        fetch_file(name + '.sig', signature, 1024, args.source_dir)
        decoded = base64.b64decode(signature.read_bytes().strip(), validate=True)
        if len(decoded) != 64:
            raise RuntimeError('The release signature is invalid.')
        (work / 'signature.bin').write_bytes(decoded)
        (work / 'public.pem').write_text(PUBLIC_KEY)
        verification = subprocess.run(['openssl', 'pkeyutl', '-verify', '-rawin', '-pubin', '-inkey', str(work / 'public.pem'), '-in', str(payload), '-sigfile', str(work / 'signature.bin')], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if verification.returncode:
            raise RuntimeError('The release signature does not match the trusted Maskeno key.')
        manifest = json.loads(payload.read_bytes())
        if type(manifest.get('schema')) is not int or manifest.get('schema') != 1 or manifest.get('version') != VERSION or manifest.get('channel') != 'stable':
            raise RuntimeError('The signed metadata describes a different release.')
        candidates = [a for a in manifest.get('artifacts', []) if a.get('platform') == 'linux-x64' and a.get('kind') == 'installer']
        if len(candidates) != 1:
            raise RuntimeError('The signed release has no unique Linux installer.')
        artifact = candidates[0]
        if artifact.get('name') != 'Maskeno-' + VERSION + '-linux-x86_64.AppImage' or type(artifact.get('size')) is not int or not 0 < artifact['size'] <= 10 * 1024 ** 3:
            raise RuntimeError('The signed Linux artifact is invalid.')
        expected = base64.b64decode(artifact.get('sha512', ''), validate=True)
        if len(expected) != 64:
            raise RuntimeError('The signed digest is invalid.')
        image = work / 'Maskeno.AppImage'
        fetch_file(artifact['name'], image, artifact['size'], args.source_dir)
        digest = hashlib.sha512()
        with image.open('rb') as reader:
            for chunk in iter(lambda: reader.read(8 * 1024 * 1024), b''):
                digest.update(chunk)
        if image.stat().st_size != artifact['size'] or digest.digest() != expected or image.open('rb').read(4) != b'\x7fELF':
            raise RuntimeError('The AppImage does not match the signed release.')
        print('Verified Maskeno ' + VERSION + ': release signature and SHA-512 match.')
        if args.verify_only:
            return
        configure_runtime(target, work)
        target.parent.mkdir(parents=True, exist_ok=True)
        fd, staged = tempfile.mkstemp(prefix='.maskeno-', dir=str(target.parent))
        try:
            with os.fdopen(fd, 'wb') as writer, image.open('rb') as reader:
                shutil.copyfileobj(reader, writer)
                os.fchmod(writer.fileno(), 0o755)
            os.replace(staged, target)
        finally:
            if os.path.exists(staged):
                os.unlink(staged)
        desktop = Path(os.environ.get('XDG_DATA_HOME', str(Path.home() / '.local/share'))) / 'applications'
        desktop.mkdir(parents=True, exist_ok=True)
        executable = str(target).replace('\\', '\\\\').replace('"', '\\"').replace('%', '%%')
        (desktop / 'maskeno.desktop').write_text('[Desktop Entry]\nType=Application\nName=Maskeno\nExec="' + executable + '" %U\nTerminal=false\nCategories=Utility;\nStartupWMClass=Maskeno\n')
        print('Installed to ' + str(target) + '. Open Maskeno from your applications menu.')
        print('This stable filename is preserved by the application updater.')


if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, RuntimeError, subprocess.CalledProcessError) as error:
        print('Installation stopped: ' + str(error), file=sys.stderr)
        sys.exit(1)
