#!/usr/bin/python3
"""Silent, task-local OpenBao browser adapter; never performs a login."""
import os
import subprocess
import sys
import uuid
from pathlib import Path
from urllib.parse import urlsplit

FIREFOX = "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"

def parse_args(name, args):
    if name == "cmd.exe":
        if len(args) != 3 or args[:2] != ["/c", "start"]:
            raise ValueError("unexpected browser invocation")
        value = args[2].replace("^&", "&")
    elif name == "xdg-open" and len(args) == 1:
        value = args[0]
    else:
        raise ValueError("unexpected browser invocation")
    url = urlsplit(value)
    if (url.scheme != "https" or not url.hostname or url.username is not None
            or url.password is not None or url.fragment or any(ord(c) < 32 for c in value)):
        raise ValueError("unexpected URL")
    return value

def launch(value):
    result = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
                             "[System.IO.Path]::GetTempPath()"],
                            capture_output=True, text=True, timeout=20, check=True)
    root = result.stdout.strip()
    if len(root) < 3 or root[1:3] != ":\\" or "\n" in root or "\r" in root:
        raise ValueError("invalid profile location")
    profile = root.rstrip("\\") + "\\cust81-warden-firefox-" + uuid.uuid4().hex
    result = subprocess.run(["wslpath", "-u", profile], capture_output=True,
                            text=True, timeout=10, check=True)
    local = Path(result.stdout.strip())
    if not local.is_absolute() or not str(local).startswith("/mnt/"):
        raise ValueError("invalid profile location")
    local.mkdir(mode=0o700)
    browser_env = dict(os.environ)
    for key in ("BAO_TOKEN", "VAULT_TOKEN", "WARDEN_CONFIG"):
        browser_env.pop(key, None)
    subprocess.Popen([FIREFOX, "-no-remote", "-profile", profile, "-new-instance",
                      "-private-window", value], stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
                     start_new_session=True, close_fds=True, env=browser_env)

def main():
    try:
        launch(parse_args(Path(sys.argv[0]).name, sys.argv[1:]))
        return 0
    except Exception:
        return 1

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