#!/usr/bin/python3
"""Boot-time sanity check for the router configuration.

Runs before router.service. Guards against config files that were truncated or
corrupted, e.g. by a power loss while the firmware rewrote config.xml:

* default.xml:    repaired from config.xml (only if config.xml itself is valid)
* config.xml:     validated (well-formed XML, root element, closing tag, all
                  top-level sections of default.xml present). On failure it is
                  restored from the last-known-good copy config.xml.good.
* config.xml.good refreshed atomically from every config.xml that passes the check.

With --refresh-good only the last step is done (no restore, default.xml untouched).
Other scripts call this after a successful `uci commit`.
"""

import os
import subprocess
import sys
import xml.etree.ElementTree as ET

CONFIG_DIR = os.environ.get("EUROGARD_CONFIG_DIR", "/app/config")
DEFAULT_XML_PATH = os.path.join(CONFIG_DIR, "default.xml")
CONFIG_XML_PATH = os.path.join(CONFIG_DIR, "config.xml")
GOOD_XML_PATH = os.path.join(CONFIG_DIR, "config.xml.good")
BROKEN_XML_PATH = os.path.join(CONFIG_DIR, "config.xml.broken")

ROOT_TAG = "config_xml"
# Only used if default.xml cannot be read to derive the section list
FALLBACK_REQUIRED_SECTIONS = [
    "lan_links",
    "system",
    "user_management",
    "wan_links",
    "web_server",
    "wireless",
]


def log(msg):
    print(msg, file=sys.stderr)
    try:
        subprocess.run(["logger", "-t", "EurogardCheckDefaultConf", msg[:1000]], check=False)
    except OSError:
        pass


def read_file(path):
    with open(path, "rb") as f:
        return f.read()


def atomic_write(path, data):
    """Write data to path so that path is either the old or the new content, never a mix."""
    tmp = f"{path}.tmp"
    # config files hold passwords: keep the mode of the file we replace, otherwise owner-only
    try:
        mode = os.stat(path).st_mode & 0o777
    except OSError:
        mode = 0o600
    with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode), "wb") as f:
        f.write(data)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, path)
    try:  # make the rename itself durable; not possible on every platform
        dir_fd = os.open(os.path.dirname(path) or ".", os.O_RDONLY)
        try:
            os.fsync(dir_fd)
        finally:
            os.close(dir_fd)
    except OSError:
        pass


def required_sections(default_path=DEFAULT_XML_PATH):
    """Top-level tags of default.xml, or the fallback list if it is unusable."""
    try:
        sections = [child.tag for child in ET.parse(default_path).getroot()]
        if sections:
            return sections
    except (OSError, ET.ParseError):
        pass
    return FALLBACK_REQUIRED_SECTIONS


def validate(path, sections):
    """Return a list of problems found in the config file at path (empty if it is fine)."""
    try:
        data = read_file(path)
    except OSError as e:
        return [f"cannot read: {e}"]
    if not data.strip():
        return ["file is empty"]
    problems = []
    if not data.rstrip().endswith(f"</{ROOT_TAG}>".encode()):
        problems.append(f"does not end with </{ROOT_TAG}> (truncated?)")
    try:
        root = ET.fromstring(data)
    except ET.ParseError as e:
        problems.append(f"not well-formed XML: {e}")
        return problems
    if root.tag != ROOT_TAG:
        problems.append(f"unexpected root element <{root.tag}>")
    present = {child.tag for child in root}
    missing = [s for s in sections if s not in present]
    if missing:
        problems.append(f"missing sections: {', '.join(missing)}")
    return problems


def check_default(sections):
    """default.xml is the template the firmware fills gaps from, keep it parsable."""
    if not os.path.exists(DEFAULT_XML_PATH):
        return
    if os.path.getsize(DEFAULT_XML_PATH) == 0:
        reason = "is empty"
    else:
        try:
            ET.parse(DEFAULT_XML_PATH)
            return
        except ET.ParseError:
            reason = "is corrupt"
    if validate(CONFIG_XML_PATH, sections):
        log(f"{DEFAULT_XML_PATH} {reason} but {CONFIG_XML_PATH} is not valid either, leaving it")
        return
    log(f"{DEFAULT_XML_PATH} {reason}, copying {CONFIG_XML_PATH} to {DEFAULT_XML_PATH}")
    atomic_write(DEFAULT_XML_PATH, read_file(CONFIG_XML_PATH))


def check_config(sections):
    if refresh_good(sections):
        return

    problems = validate(CONFIG_XML_PATH, sections)
    log(f"{CONFIG_XML_PATH} is broken: {'; '.join(problems)}")
    good_problems = validate(GOOD_XML_PATH, sections)
    if good_problems:
        log(f"Cannot restore, {GOOD_XML_PATH} is unusable: {'; '.join(good_problems)}")
        return
    # Keep the broken file for analysis, but never replace an earlier one with an empty file
    if os.path.exists(CONFIG_XML_PATH) and os.path.getsize(CONFIG_XML_PATH) > 0:
        try:
            atomic_write(BROKEN_XML_PATH, read_file(CONFIG_XML_PATH))
        except OSError as e:
            log(f"Could not keep a copy of the broken config: {e}")
    atomic_write(CONFIG_XML_PATH, read_file(GOOD_XML_PATH))
    log(f"Restored {CONFIG_XML_PATH} from {GOOD_XML_PATH}, broken file kept as {BROKEN_XML_PATH}")


def refresh_good(sections):
    """Copy config.xml to config.xml.good if it is valid. Returns False if config.xml is not valid."""
    problems = validate(CONFIG_XML_PATH, sections)
    if problems:
        log(f"Not updating {GOOD_XML_PATH}, {CONFIG_XML_PATH} is broken: {'; '.join(problems)}")
        return False
    data = read_file(CONFIG_XML_PATH)
    # Skip the flash write if nothing changed
    if not os.path.exists(GOOD_XML_PATH) or read_file(GOOD_XML_PATH) != data:
        atomic_write(GOOD_XML_PATH, data)
        log(f"{CONFIG_XML_PATH} is valid, updated {GOOD_XML_PATH}")
    return True


def main(argv=None):
    argv = sys.argv[1:] if argv is None else argv
    sections = required_sections()
    if "--refresh-good" in argv:
        try:
            return 0 if refresh_good(sections) else 1
        except Exception as e:
            log(f"refresh_good failed: {e!r}")
            return 1
    for check in (check_default, check_config):
        try:
            check(sections)
        except Exception as e:  # never block the boot because of this script
            log(f"{check.__name__} failed: {e!r}")
    return 0


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