#!/opt/edge/venv/bin/python3.11

import errno
import subprocess
import sys
import ujson

from pathlib import PurePath
from typing import Dict, List, Union

_BIN_NAME = PurePath(sys.argv[0]).name
_TARGET_PATH = './info.json'


class AppError(Exception):
    pass


def stdout(text: str) -> None:
    print(f'[{_BIN_NAME}] {text}')


def stderr(text: str) -> None:
    print(f'[{_BIN_NAME}] {text}', file=sys.stderr)


def usage() -> None:
    stderr('usage:')
    stderr(f'\t# {_BIN_NAME} create')


def load_json3(filepath: str, **kwargs) -> Union[Dict, List]:
    """
    :raise FsError:
    """
    try:
        try:
            with open(filepath) as json_file:
                jnode = ujson.load(json_file)
                return jnode

        except IOError as x:
            stderr(f'fail: IOError {filepath} ({errno.errorcode[x.errno]})')
            raise AppError

        except ValueError as x:
            stderr(f'fail: ValueError {filepath} ({x})')
            raise AppError

    except AppError:
        if 'default' not in kwargs:
            raise

    return kwargs.get('default')


def _get_db_semver() -> str:
    cli_params = ' '.join(["dpkg-query", "--show", "--showformat='${Version}'", "edge-db4"])
    cli_result = subprocess.run(cli_params, shell=True, capture_output=True, text=True, encoding='ascii')
    if cli_result.returncode != 0:
        stderr('fail: InternalError <{}> ({}, {}, {})'.format(
            cli_result.args, cli_result.returncode, cli_result.stdout, cli_result.stderr))
        raise AppError

    return cli_result.stdout


def _get_edge_semver() -> str:
    with open('/opt/edge/semver', 'r') as text_file:
        semver = text_file.readline()

    return semver.strip()


def _get_os_name() -> str:
    with open('/etc/os-release', 'r') as text_file:
        lines = text_file.readlines()

    for line in lines:
        if line.startswith('VERSION_CODENAME='):
            param, value = line.split('=', 1)
            return value.strip('\n')

    raise AppError


def _get_hw_info() -> List[str] | None:
    about_jnode = load_json3('/etc/edge/setupstore/about.json')
    return about_jnode.get('hw', None)


def _get_origins() -> List[str]:
    conf = load_json3('/etc/edge/webserver.0/main.conf')
    medias: List[Dict] = conf.get('Media') or list()

    origins_list = []
    for media in medias:
        origins_list.append(media['origin'])

    return origins_list


def _get_jnode() -> Dict:
    jnode = {
        'db-semver': _get_db_semver(),
        'edge-semver': _get_edge_semver(),
        'os': _get_os_name(),
        'origins': _get_origins()
    }

    hw_info = _get_hw_info()
    if hw_info is not None:
        jnode['hw'] = hw_info

    return jnode


def _handle_create() -> None:
    jnode = _get_jnode()

    try:
        with open(_TARGET_PATH, 'w') as json_file:
            ujson.dump(jnode, json_file, ensure_ascii=False, indent=2)

    except IOError as x:
        stderr(f'fail: save <{_TARGET_PATH}> ({errno.errorcode[x.errno]})')
        raise AppError


def _handle_restore() -> None:
    jnode = _get_jnode()
    backup_jnode = load_json3(_TARGET_PATH, default=dict())

    if jnode['db-semver'] != backup_jnode['db-semver']:
        stderr(f'fail: wrong db-semver')
        raise AppError

    elif jnode['edge-semver'] != backup_jnode['edge-semver']:
        stderr(f'fail: wrong edge-semver')
        raise AppError

    elif jnode['os'] != backup_jnode['os']:
        stderr(f'fail: wrong os')
        raise AppError

    jnode_hw = jnode.get('hw')
    backup_hw = backup_jnode.get('hw')

    if backup_hw is not None:
        if jnode_hw is not None:
            if backup_hw != jnode_hw:
                stderr(f'fail: wrong hw')
                raise AppError


def _main(argv: List[str]) -> None:
    if len(argv) != 2:
        stderr('fail: invalid args')
        usage()
        raise AppError

    action = argv[1]
    if action == 'create':
        stdout('exec: create')
        _handle_create()
        stdout('done: create')

    elif action == 'restore':
        stdout('exec: restore')
        _handle_restore()
        stdout('done: restore')

    else:
        stderr(f'fail: unsupported (action:{action})')
        usage()
        raise AppError


if __name__ == '__main__':
    exit_code = 1
    try:
        _main(sys.argv)
        exit_code = 0
    except AppError:
        pass

    sys.exit(exit_code)
