#!/usr/bin/env python3
"""Checks of the credentials files (option credentialsFile, ~/.netrc) with
BNC as Ntrip client and as uploading source against tools/fakecaster.py
(--auth: only the expected user and password are accepted). Every scenario
runs with its own HOME directory, so ~/.netrc is under control.

    tests/tools/cred_check.py [--bnc PATH]      exit code 1 if a check fails

Download (Ntrip 2 unless noted):
  password in the configuration file (as before, hint in the log)
  user only, ~/.netrc with two users for the host (and a macdef)
  $NETRC: entry 'machine host:port' preferred over 'machine host'
  BNC format (credentialsFile): exact port preferred over '*', quoted password
  BNC format without port: '<host> <user> <password>'
  URL without user: no credentials sent although ~/.netrc has the host
  user without entry: logged, rejected by the caster
  ~/.netrc readable for others: not used (logged)
  netrc 'default' entry: not used
  Ntrip 1 with ~/.netrc
Upload:
  Ntrip 2, user with empty password, BNC format file
  Ntrip 1, no user and empty password, BNC format entry with user '-'
"""

import argparse
import glob
import os
import shutil
import subprocess
import sys
import time

TOOLS = os.path.dirname(os.path.abspath(__file__))
TESTS = os.path.dirname(TOOLS)
ROOT = os.path.dirname(TESTS)
WORK = os.path.join(TESTS, "work", "cred_check")
SERVE_RAW = os.path.join(TESTS, "data", "crafted_limits.raw")
UPLOAD_RAW = os.path.join(TESTS, "data", "upload_rtnet_5min.raw")


def run(bnc, name, port, auth, bnc_args, files=None, env_extra=None, upload=False):
    """Fake caster on 127.0.0.1:port, BNC with HOME=<work>/home; returns
    (caster output, BNC log)."""
    d = os.path.join(WORK, name)
    home = os.path.join(d, "home")
    os.makedirs(os.path.join(d, "Output"))
    os.makedirs(home)
    os.symlink(os.path.join(ROOT, "Example_Configs", "Input"), os.path.join(d, "Input"))
    for path, (text, mode) in (files or {}).items():
        path = path.replace("~", home)
        with open(path, "w") as f:
            f.write(text.replace("PORT", str(port)))
        os.chmod(path, mode)
    caster = [sys.executable, "-I", os.path.join(TOOLS, "fakecaster.py"), "--port", str(port),
              "--out", os.path.join(d, "Output", "upload.raw"), "--time", "2026-10-01T09:33:00",
              "--timeout", "6"]
    if not upload:
        caster += ["--serve", SERVE_RAW]
    for a in auth:
        caster += ["--auth", a]
    fc = subprocess.Popen(caster, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    fc.stdout.readline()  # "listening"
    env = dict(os.environ, QT_QPA_PLATFORM="offscreen", LC_ALL="C", TZ="UTC", HOME=home)
    env.pop("NETRC", None)
    env.update({k: v.replace("~", home) for k, v in (env_extra or {}).items()})
    args = [a.replace("~", home).replace("PORT", str(port)) for a in bnc_args]
    cmd = [bnc, "--nw", "--platform", "offscreen"] + args
    with open(os.path.join(d, "bnc.out"), "wb") as out:
        if upload:
            subprocess.run(cmd, cwd=d, stdout=out, stderr=subprocess.STDOUT, env=env, timeout=300)
        else:
            p = subprocess.Popen(cmd, cwd=d, stdout=out, stderr=subprocess.STDOUT, env=env)
            time.sleep(8)
            p.send_signal(2)
            p.wait(30)
    out = fc.communicate(timeout=120)[0]
    with open(os.path.join(d, "caster.out"), "w") as f:
        f.write(out)
    log = "".join(open(f, errors="replace").read() for f in glob.glob(os.path.join(d, "Output", "*.log*")))
    return out, log


def download(bnc, name, port, url_user, auth, files=None, env_extra=None, extra=(), version="2"):
    mp = "//%s127.0.0.1:%d/TEST RTCM_3 DEU 50 8 no %s" % (url_user, port, version)
    return run(bnc, name, port, auth,
               ["--conf", os.path.join(ROOT, "Example_Configs", "22_Empty.bnc"),
                "-key", "mountPoints", mp, "-key", "logFile", "Output/bnc.log"] + list(extra),
               files, env_extra)


def upload(bnc, name, port, version, user, auth, files, extra=()):
    mp = "127.0.0.1,%d,CLOCK,%s,%s,,IGS20,IGS-SSR,0,,,,,,,0 byte(s)," % (port, version, user)
    return run(bnc, name, port, auth,
               ["--conf", os.path.join(ROOT, "Example_Configs", "16_Upload.bnc"),
                "--file", UPLOAD_RAW, "-key", "uploadMountpointsOut", mp] + list(extra),
               files, upload=True)


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--bnc", default=os.path.join(ROOT, "bnc"))
    args = ap.parse_args()
    bnc = os.path.abspath(args.bnc)
    shutil.rmtree(WORK, ignore_errors=True)
    failed = 0

    def check(name, ok, caster):
        nonlocal failed
        lines = [l for l in caster.splitlines() if l.startswith(("auth", "served", "received"))]
        summary = ", ".join(sorted(set(lines)))
        print("%-6s %-46s %s" % ("PASS" if ok else "FAIL", name, summary), flush=True)
        failed += not ok

    def served(c):
        return any(l.startswith("served ") and int(l.split()[1]) > 0 for l in c.splitlines())

    def rejected(c):
        return any(l.startswith("auth ") and l.endswith(" rejected") for l in c.splitlines())

    def received(c):
        return any(l.startswith("received ") and int(l.split()[1]) > 0 for l in c.splitlines())

    netrc_two_users = ("macdef init\ncd /tmp\n\n"
                       "# two accounts on the same caster\n"
                       "machine 127.0.0.1 login other password x\n"
                       "machine 127.0.0.1 login bnc password right\n")

    c, log = download(bnc, "config_password", 21301, "bnc:right@", ["bnc:right"])
    check("download: password in the configuration file", served(c) and "auth bnc accepted" in c
          and "password in the configuration file" in log, c)

    c, log = download(bnc, "netrc_two_users", 21302, "bnc@", ["bnc:right"],
                      {"~/.netrc": (netrc_two_users, 0o600)})
    check("download: ~/.netrc, two users for the host", served(c) and "auth bnc accepted" in c
          and not rejected(c) and "configuration file" not in log, c)

    c, log = download(bnc, "netrc_port", 21303, "bnc@", ["bnc:right"],
                      {"~/other_netrc": ("machine 127.0.0.1 login bnc password wrong\n"
                                         "machine 127.0.0.1:PORT login bnc password right\n", 0o600)},
                      {"NETRC": "~/other_netrc"})
    check("download: $NETRC, machine host:port preferred", served(c) and not rejected(c), c)

    c, log = download(bnc, "bnc_format", 21304, "bnc@", ["bnc:my secret"],
                      {"~/bnc.credentials": ("# host port user password\n"
                                             "127.0.0.1  *    bnc  wrong\n"
                                             "127.0.0.1  PORT bnc  \"my secret\"\n", 0o600)},
                      extra=["-key", "credentialsFile", "~/bnc.credentials"])
    check("download: BNC format, exact port, quoted", served(c) and not rejected(c), c)

    c, log = download(bnc, "bnc_format_3", 21312, "bnc@", ["bnc:three"],
                      {"~/bnc.credentials": ("127.0.0.1 other x\n127.0.0.1 bnc three\n", 0o600)},
                      extra=["-key", "credentialsFile", "~/bnc.credentials"])
    check("download: BNC format without port", served(c) and not rejected(c), c)

    c, log = download(bnc, "anonymous", 21305, "", [],
                      {"~/.netrc": (netrc_two_users, 0o600)})
    check("download: URL without user stays anonymous", served(c) and "auth none" in c
          and "auth bnc" not in c and "auth other" not in c, c)

    c, log = download(bnc, "no_entry", 21306, "bnc@", ["bnc:right"],
                      {"~/.netrc": ("machine 127.0.0.1 login other password x\n", 0o600)})
    check("download: no entry for the user", not served(c) and "auth bnc rejected" in c
          and "no password" in log, c)

    c, log = download(bnc, "netrc_readable", 21307, "bnc@", ["bnc:right"],
                      {"~/.netrc": ("machine 127.0.0.1 login bnc password right\n", 0o644)})
    check("download: ~/.netrc readable for others", not served(c) and "readable for other users" in log, c)

    c, log = download(bnc, "netrc_default", 21308, "bnc@", ["bnc:right"],
                      {"~/.netrc": ("default login bnc password right\n", 0o600)})
    check("download: netrc default entry not used", not served(c) and "no password" in log, c)

    c, log = download(bnc, "ntrip1", 21309, "bnc@", ["bnc:right"],
                      {"~/.netrc": (netrc_two_users, 0o600)}, version="1")
    check("download: Ntrip 1, ~/.netrc", served(c) and "auth bnc accepted" in c and not rejected(c), c)

    c, log = upload(bnc, "upload_v2", 21310, "2", "bnc", ["bnc:up2"],
                    {"~/bnc.credentials": ("127.0.0.1 PORT bnc up2\n", 0o600)},
                    ["-key", "credentialsFile", "~/bnc.credentials"])
    check("upload: Ntrip 2, password from file", received(c) and not rejected(c), c)

    c, log = upload(bnc, "upload_v1", 21311, "1", "", [":up1"],
                    {"~/bnc.credentials": ("127.0.0.1 PORT - up1\n", 0o600)},
                    ["-key", "credentialsFile", "~/bnc.credentials"])
    check("upload: Ntrip 1, entry without user", received(c) and not rejected(c), c)

    print("%d check(s) failed, details in %s" % (failed, os.path.relpath(WORK, ROOT)))
    return 1 if failed else 0


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