#!/usr/bin/env python3
"""Update lab: the addon's own update (wcs/skin/update.py, update_apply.py) live, in the clean Mac Kodi of
fresh_kodi.py (docs/plan/skin-optimization/020-tv-handover.md, phase A).

The update reads the index named by the installed repository.milionar, and only an https one. So the lab serves its own
HTTPS repository on 127.0.0.1 with a certificate made for this run, trusted only inside the test profile (its copy of
script.module.certifi), and points the test profile's repository addon at it. Every package is the workspace build with
one change, so each way an update can go wrong is tried for real. Never the workspace Kodi: everything here lives under
the root of fresh_kodi.py.

The site has the hosting's layout: repo/ (the stable series, Kodi's repository) and beta/ (the beta series, read only by
the update window, docs/plan/skin-milionar/340-beta-channel.md).

Commands (same MILIONAR_FRESH_ROOT as fresh_kodi.py, after its `up` and `install` and the guide):
  serve                      certificate, trust in the test profile, HTTPS server, the repository addon pointed at it
  publish VARIANT VERSION [--series beta]
                             the workspace build as VERSION, changed by VARIANT, into the series (stable: repo/):
                             good, crc (a damaged file), wrongversion (the package says another version),
                             brokenservice (service.py does not start), newdep (a dependency not installed yet),
                             baddep (a dependency no repository has), missing (in the index, no package)
  lower VERSION              the installed addon claims an older version (addon.xml, UpdateLocalAddons)
  open                       the update window, as the gear's menu opens it
  state                      the window's properties, the installed version, addons/temp
  stop                       the HTTPS server stops (the repository is unreachable)
"""
import argparse
import http.server
import json
import os
import re
import shutil
import signal
import ssl
import subprocess
import sys
import time
import zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import fresh_kodi as fk                      # noqa: E402

PORT = 8766
LAB = os.path.join(fk.ROOT, 'lab')
SITE = os.path.join(LAB, 'site')
STATE = os.path.join(LAB, 'lab.json')
CERT, KEY = os.path.join(LAB, 'cert.pem'), os.path.join(LAB, 'key.pem')
URL = 'https://127.0.0.1:{}/'.format(PORT)
NEW_DEPENDENCY = ('script.module.beautifulsoup4', '4.6.2')     # in Kodi's own repository, not needed by the addon
UNKNOWN_DEPENDENCY = ('script.module.milionar.nowhere', '1.0.0')  # in no repository
FIELDS = ('state', 'installed', 'installed_build', 'available', 'available_build', 'available_caption', 'headline', 'text',
          'primary', 'next', 'primary_version', 'alternate', 'alternate_version', 'busy', 'target')


def _state(**update):
    data = {}
    if os.path.exists(STATE):
        with open(STATE) as handle:
            data = json.load(handle)
    if update:
        data.update(update)
        with open(STATE, 'w') as handle:
            json.dump(data, handle)
    return data


def _addon_xml(path):
    with open(path, encoding='utf-8') as handle:
        return handle.read()


def _base_zip():
    folder = os.path.join(fk.ROOT, 'repo', fk.ADDON_ID)
    found = sorted(name for name in os.listdir(folder) if name.endswith('.zip'))
    if not found:
        raise SystemExit('no workspace build in ' + folder + ' (fresh_kodi.py up builds it)')
    return os.path.join(folder, found[-1])


def _versioned(xml, version):
    return re.sub(r'(<addon\b[^>]*\bversion=")[^"]+(")', r'\g<1>{}\g<2>'.format(version), xml, count=1)


def _write_zip(target, files):
    with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as archive:
        for name, data in files:
            archive.writestr(name, data)


def cmd_serve(args):
    os.makedirs(SITE, exist_ok=True)
    if not os.path.exists(CERT):
        subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '2', '-subj', '/CN=127.0.0.1',
                        '-addext', 'subjectAltName=IP:127.0.0.1', '-keyout', KEY, '-out', CERT],
                       check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    bundles = []
    for top, _dirs, names in os.walk(os.path.join(fk.PROFILE, 'addons')):
        bundles += [os.path.join(top, name) for name in names if name == 'cacert.pem']
    if not bundles:
        raise SystemExit('no cacert.pem in the test profile (is the addon installed?)')
    with open(CERT) as handle:
        cert = handle.read()
    for bundle in bundles:                              # trust only inside the test profile
        with open(bundle) as handle:
            known = handle.read()
        if cert not in known:
            with open(bundle, 'a') as handle:
                handle.write('\n' + cert)
    repo = os.path.join(fk.PROFILE, 'addons', fk.REPO_ID, 'addon.xml')
    xml = _addon_xml(repo)
    xml = re.sub(r'(<info[^>]*>)[^<]*(</info>)', r'\g<1>{}repo/addons.xml\g<2>'.format(URL), xml)
    xml = re.sub(r'<checksum>[^<]*</checksum>', '<checksum>{}repo/addons.xml.md5</checksum>'.format(URL), xml)
    xml = re.sub(r'(<datadir[^>]*>)[^<]*(</datadir>)', r'\g<1>{}repo/\g<2>'.format(URL), xml)
    with open(repo, 'w', encoding='utf-8') as handle:
        handle.write(xml)
    _start_server()
    print('HTTPS repository on {} (trusted in {} bundle(s) of the test profile)'.format(URL, len(bundles)))


def _start_server():
    cmd_stop(None, quiet=True)
    server = subprocess.Popen([sys.executable, os.path.abspath(__file__), '_server'], stdout=subprocess.DEVNULL,
                              stderr=subprocess.DEVNULL)
    _state(server=server.pid)
    time.sleep(0.5)


def cmd__server(args):
    class Handler(http.server.SimpleHTTPRequestHandler):
        def __init__(self, *a, **k):
            super().__init__(*a, directory=SITE, **k)

        def log_message(self, *a):
            pass
    httpd = http.server.ThreadingHTTPServer(('127.0.0.1', PORT), Handler)
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    context.load_cert_chain(CERT, KEY)
    httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
    httpd.serve_forever()


def cmd_stop(args, quiet=False):
    pid = _state().get('server') if os.path.exists(STATE) else None
    if pid:
        try:
            os.kill(pid, signal.SIGTERM)
        except OSError:
            pass
        _state(server=None)
    if not quiet:
        print('HTTPS repository stopped')


def cmd_publish(args):
    version, variant = args.version, args.variant
    prefix = fk.ADDON_ID + '/'
    series = os.path.join(SITE, 'repo' if args.series == 'stable' else 'beta')
    with zipfile.ZipFile(_base_zip()) as archive:
        files = [(info.filename, archive.read(info)) for info in archive.infolist()]
    xml = dict(files)[prefix + 'addon.xml'].decode('utf-8')
    index_xml = _versioned(xml, version)
    package_xml = _versioned(xml, version + '1') if variant == 'wrongversion' else index_xml
    if variant in ('newdep', 'baddep'):
        dep = '<import addon="{}" version="{}"/>'.format(*(NEW_DEPENDENCY if variant == 'newdep' else UNKNOWN_DEPENDENCY))
        package_xml = package_xml.replace('<requires>', '<requires>' + dep, 1)
        index_xml = package_xml
    changed = []
    for name, data in files:
        if name == prefix + 'addon.xml':
            data = package_xml.encode('utf-8')
        elif name == prefix + 'service.py' and variant == 'brokenservice':
            data = b'def broken(:\n'
        elif variant == 'brokenservice' and name.startswith(prefix + '__pycache__/service.'):
            continue                                     # no old bytecode that would still run
        changed.append((name, data))
    package = os.path.join(series, fk.ADDON_ID, '{}-{}.zip'.format(fk.ADDON_ID, version))
    shutil.rmtree(os.path.join(series, fk.ADDON_ID), ignore_errors=True)
    os.makedirs(os.path.dirname(package))
    if variant != 'missing':
        _write_zip(package, changed)
    if variant == 'crc':                                 # one byte of main.py's data: its CRC check fails
        with zipfile.ZipFile(package) as archive:
            info = archive.getinfo(prefix + 'main.py')
        with open(package, 'r+b') as handle:
            handle.seek(info.header_offset + 26)
            name_len, extra_len = int.from_bytes(handle.read(2), 'little'), int.from_bytes(handle.read(2), 'little')
            spot = info.header_offset + 30 + name_len + extra_len + info.compress_size // 2
            handle.seek(spot)
            byte = handle.read(1)
            handle.seek(spot)
            handle.write(bytes([byte[0] ^ 0xFF]))
    strip = lambda text: re.sub(r'^\s*<\?xml[^>]*\?>\s*', '', text).strip()
    entries = [strip(index_xml)]
    if args.series == 'stable':                          # Kodi's repository lists itself too; the beta index only the addon
        entries.append(strip(_addon_xml(os.path.join(fk.PROFILE, 'addons', fk.REPO_ID, 'addon.xml'))))
    index = '<?xml version="1.0" encoding="UTF-8"?>\n<addons>\n{}\n</addons>\n'.format('\n'.join(entries))
    with open(os.path.join(series, 'addons.xml'), 'w', encoding='utf-8') as handle:
        handle.write(index)
    import hashlib
    with open(os.path.join(series, 'addons.xml.md5'), 'w') as handle:
        handle.write(hashlib.md5(index.encode('utf-8')).hexdigest())
    print('published {} as {} ({})'.format(variant, version, args.series))


def cmd_lower(args):
    path = os.path.join(fk.PROFILE, 'addons', fk.ADDON_ID, 'addon.xml')
    xml = _versioned(_addon_xml(path), args.version)
    with open(path, 'w', encoding='utf-8') as handle:
        handle.write(xml)
    fk.builtin('UpdateLocalAddons')
    deadline = time.monotonic() + 20
    while time.monotonic() < deadline:
        if _installed() == args.version:
            print('installed version now {}'.format(args.version))
            return
        time.sleep(0.5)
    raise SystemExit('Kodi still reports {}'.format(_installed()))


def _installed():
    answer = fk.rpc('Addons.GetAddonDetails', {'addonid': fk.ADDON_ID, 'properties': ['version', 'enabled']})
    if 'error' in answer:
        return 'unknown to Kodi'
    details = (answer.get('result') or {}).get('addon') or {}
    return details.get('version', '') if details.get('enabled') else 'disabled ' + details.get('version', '')


def cmd_open(args):
    fk.builtin('RunPlugin(plugin://{}/?action=skin_update)'.format(fk.ADDON_ID))
    print('update window asked for')


def cmd_state(args):
    labels = ['Window(Home).Property(milionar.update.{})'.format(name) for name in FIELDS] + [
        'Window(Home).Property(milionar.service)', 'Window.IsActive(1124)']
    values = fk.rpc('XBMC.GetInfoLabels', {'labels': labels})['result']
    temp = os.path.join(fk.PROFILE, 'addons', 'temp')
    out = {label.split('(')[-1].rstrip(')'): values.get(label, '') for label in labels}
    out.update({'installed': _installed(), 'addons/temp': sorted(os.listdir(temp)) if os.path.isdir(temp) else []})
    print(json.dumps(out, ensure_ascii=False, indent=1))


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = parser.add_subparsers(dest='cmd', required=True)
    for name in ('serve', 'stop', 'open', 'state', '_server'):
        sub.add_parser(name)
    p = sub.add_parser('publish')
    p.add_argument('variant', choices=('good', 'crc', 'wrongversion', 'brokenservice', 'newdep', 'baddep', 'missing'))
    p.add_argument('version')
    p.add_argument('--series', choices=('stable', 'beta'), default='stable')
    p = sub.add_parser('lower')
    p.add_argument('version')
    args = parser.parse_args()
    globals()['cmd_' + args.cmd](args)


if __name__ == '__main__':
    main()
