repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
nixmod.pyPython1,090 lines48.7 KiBraw download
#!/usr/bin/env python3
"""nixmod — make and remove NixDaemon modules from templates.

  nixmod new firefox                     enable a program using its pinned Home Manager options
  nixmod new gallery-dl --set settings.extractor.base-directory=~/Downloads/gallery-dl
  nixmod new --nixos steam               the same from NixOS → modules/features/steam.nix
  nixmod new -t script backup            a shell command, packaged
  nixmod new -t service --nixos tunnel   a hand-written systemd service (+ timer)
  nixmod new -t packages recon           a bundle of packages
  nixmod new -t config foot              config files in ~/.config, ~ or out of the store
  nixmod new -t feature --nixos lab      a daemon.lab.enable switch with options
  nixmod new -t package mytool           your own derivation (nix build .#mytool)
  nixmod firefox                         `new` is the default command

  nixmod rm firefox                      delete it: the file, its import line, git
  nixmod list                            modules nixmod made, and the templates
  nixmod search fire                     programs.* / services.* / packages matching
  nixmod doc programs.git                every option of a tree, as text
  nixmod check gallery-dl                check an edited module and the current host

Each file declares flake.homeModules.<name> / nixosModules.<name> (or
perSystem.packages.<name>) the way every other module here does, carries a
"Started by nixmod" line so `nixmod rm` knows it may delete it, is `git add`ed
and is named in the host's imports list. Options come from this flake's own
nixosConfigurations, so they are the ones flake.lock pins.
"""
from __future__ import annotations

import argparse
import datetime
import json
import os
import re
import shutil
import shlex
import socket
import subprocess
import sys
import textwrap
from pathlib import Path

PROBE = Path(os.environ.get("NIXMOD_PROBE", Path(__file__).with_name("options.nix")))
MARK = "Started by nixmod"
WIDTH = 78
COMMANDS = ("new", "rm", "list", "search", "doc", "check", "templates")

TEMPLATES = {
    "program": "a Home Manager / NixOS program: enable, editable settings, upstream examples (default)",
    "packages": "a bundle of packages, one per line with a reason",
    "script": "a command of your own: writeShellApplication (or Python), on PATH",
    "service": "a hand-written systemd service, with a timer and hardening commented",
    "config": "config files: xdg.configFile, home.file, out-of-store symlinks (home only)",
    "feature": "a switch, daemon.<name>.enable, with typed options and mkIf",
    "package": "your own derivation as perSystem.packages.<name>: fetchFromGitHub, mkDerivation",
}

# Where each kind of module is named, per host: host → kind → (file, entry).
WIRING = {
    "nixos": {
        "home": ("modules/home/default.nix", "{name}"),
        "nixos": ("modules/hosts/laptop/configuration.nix", "{name}"),
    },
    "nixdaemon": {
        "home": ("modules/hosts/generic/home.nix", "{name}"),
        "nixos": ("modules/hosts/generic/default.nix", "self.nixosModules.{name}"),
    },
}
ATTR = {"home": "homeModules", "nixos": "nixosModules"}


def die(msg: str) -> None:
    print(f"nixmod: {msg}", file=sys.stderr)
    sys.exit(1)


def run(*cmd: str, **kw) -> subprocess.CompletedProcess:
    return subprocess.run(list(cmd), capture_output=True, text=True, **kw)


# ── the flake ──────────────────────────────────────────────────────────────

def find_repo(arg: str | None) -> Path:
    tries = [arg, os.environ.get("NIXDAEMON"), os.environ.get("NH_FLAKE")]
    top = run("git", "rev-parse", "--show-toplevel")
    if top.returncode == 0:
        tries.append(top.stdout.strip())
    tries.append(str(Path.home() / "NixDaemon"))
    for t in tries:
        if t and (Path(t) / "modules/parts.nix").is_file():
            return Path(t).resolve()
    die("no NixDaemon checkout found (try --repo DIR or NIXDAEMON=DIR)")
    raise SystemExit


def nix_eval(repo: Path, **args: str | None) -> dict:
    def lit(v):
        return "null" if v is None else json.dumps(v)

    expr = "import {} {{ repo = {}; {} }}".format(
        PROBE, json.dumps(f"git+file://{repo}"), " ".join(f"{k} = {lit(v)};" for k, v in args.items()))
    r = run("nix", "eval", "--impure", "--json", "--no-warn-dirty", "--expr", expr)
    if r.returncode != 0:
        die("evaluating the flake failed:\n" + r.stderr.strip())
    return json.loads(r.stdout)


def pick_host(repo: Path, want: str | None) -> str:
    r = run("nix", "eval", "--json", "--no-warn-dirty", f"{repo}#nixosConfigurations",
            "--apply", "builtins.attrNames")
    known = json.loads(r.stdout) if r.returncode == 0 else []
    if r.returncode != 0:
        die("reading the available hosts failed:\n" + r.stderr.strip())
    host = want or (socket.gethostname() if socket.gethostname() in known else None) \
        or (known[0] if len(known) == 1 else None)
    if not host or host not in known:
        die(f"cannot select a host (have: {', '.join(known) or 'none'}); use --host NAME")
    return host


def check_hosts(repo: Path, hosts=None) -> bool:
    """Evaluate the selected hosts the way a rebuild would, without building."""
    ok = True
    for host in hosts if hosts is not None else WIRING:
        print(f"check   {host}: evaluating (no build or activation)", flush=True)
        r = run("nix", "eval", "--raw", "--no-warn-dirty",
                f"{repo}#nixosConfigurations.{host}.config.system.build.toplevel.drvPath")
        if r.returncode == 0:
            print(f"check   {host}: evaluates")
        else:
            ok = False
            print(f"check   {host}: FAILS\n" + textwrap.indent(r.stderr.strip(), "        "))
    return ok


def git_add(repo: Path, *paths: str) -> None:
    if (repo / ".git").exists():
        run("git", "-C", str(repo), "add", "--", *paths)


# ── option docs → Nix ──────────────────────────────────────────────────────

def split_path(name: str) -> list[str]:
    """`profiles.<name>."a.b".x` → ['profiles', '<name>', '"a.b"', 'x']"""
    return re.findall(r'"(?:[^"\\]|\\.)*"|[^.]+', name)


def attr(seg: str) -> str:
    if seg.startswith('"'):
        return seg
    if seg == "<name>":
        return '"<name>"'  # a placeholder key: rename it (a profile, a host, a user …)
    return data_attr(seg)


def data_attr(seg: str) -> str:
    """A data key is never a preformatted Nix expression."""
    if "\x00" in seg:
        die("Nix attribute names cannot contain null bytes")
    return seg if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_'-]*", seg) else \
        json.dumps(seg, ensure_ascii=False).replace("${", "\\${")


def to_nix(v, indent: int = 0, *, literals: bool = True) -> str:
    pad = "  " * (indent + 1)
    if literals and isinstance(v, dict) and v.get("_type") in ("literalExpression", "literalMD"):
        return v["text"].strip()
    if v is None:
        return "null"
    if isinstance(v, bool):
        return "true" if v else "false"
    if isinstance(v, (int, float)):
        return str(v)
    if isinstance(v, str):
        if "\x00" in v:
            die("Nix strings cannot contain null bytes")
        if any(ord(c) < 32 and c not in "\n\r\t" for c in v):
            # Nix quoted strings have fewer escapes than JSON. Preserve unusual
            # control characters through its JSON decoder instead of losing them.
            encoded = to_nix(json.dumps(v), literals=False)
            return f"(builtins.fromJSON {encoded})"
        if literals and "\n" in v:
            return "''\n" + textwrap.indent(v.replace("''", "'''").replace("${", "''${"), pad) + "  " * indent + "''"
        return json.dumps(v, ensure_ascii=False).replace("${", "\\${")
    if isinstance(v, list):
        return "[ " + " ".join(to_nix(x, indent, literals=literals) for x in v) + " ]" if v else "[ ]"
    if isinstance(v, dict):
        if not v:
            return "{ }"
        body = "".join(f"{pad}{data_attr(k)} = {to_nix(x, indent + 1, literals=literals)};\n" for k, x in v.items())
        return "{\n" + body + "  " * indent + "}"
    return json.dumps(str(v))


def placeholder(typ: str) -> str:
    t = (typ or "").lower()
    if t.startswith("null or "):
        return "null"
    if "boolean" in t:
        return "false"
    if t.startswith("list of"):
        return "[ ]"
    if t.startswith("attribute set") or "submodule" in t or "lazy attribute set" in t:
        return "{ }"
    if "integer" in t or "number" in t:
        return "0"
    if t.startswith("absolute path") or t == "path":
        return "./file"
    if "package" in t:
        return "pkgs.hello"
    if "lines" in t or "strings concatenated" in t:
        return "''\n  ''"
    return '""'


def describe(desc) -> list[str]:
    if isinstance(desc, dict):
        desc = desc.get("text")
    if not desc:
        return []
    text = desc.strip().split("\n\n")[0]
    text = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", text)      # [text](url) → text
    text = re.sub(r"\{(?:option|var|env|file|command|manpage)\}`([^`]*)`", r"\1", text)
    text = re.sub(r"\s+", " ", text).strip()
    sentences = re.split(r"(?<=[.!?])\s", text)
    short = sentences[0] if len(sentences[0]) > 30 or len(sentences) == 1 else " ".join(sentences[:2])
    lines = textwrap.wrap(short, 70, break_long_words=False, break_on_hyphens=False)
    return lines[:3] if len(lines) <= 3 else lines[:2] + [lines[2] + " …"]


def noise(rel: str) -> bool:
    """Options nobody sets in a host config: module internals, macOS-only knobs."""
    segs = split_path(rel)
    return ("_module" in segs or "darwin" in rel.lower()
            or (len(segs) >= 2 and segs[-2] == "meta" and segs[-1] in ("maintainers", "teams")))


def render_option(rel: str, o: dict, ind: str) -> list[str]:
    """One option as a commented block, ready to uncomment."""
    segs = split_path(rel)
    typ = o.get("type") or "unspecified"
    if len(typ) > 60:
        typ = typ[:57].rsplit(" ", 1)[0] + " …"
    out = [f"{ind}# {rel} — {typ}"]
    out += [f"{ind}#   {l}" for l in describe(o.get("description"))]
    default, example = o.get("default"), o.get("example")
    dtext = to_nix(default) if default is not None else None
    if "*" in segs:
        # An option inside a list of submodules has no attribute path of its own.
        if dtext:
            out.append(f"{ind}#   default: {dtext.splitlines()[0]}")
        return out
    value = to_nix(example) if example is not None else dtext or placeholder(typ)
    if example is not None and dtext and dtext != value and "\n" not in dtext and len(dtext) < 60:
        out.append(f"{ind}#   default: {dtext}")
    lhs = ".".join(attr(s) for s in segs)
    out += [f"{ind}# {l}" for l in f"{lhs} = {value};".splitlines()]
    return out


def path_segments(path: str) -> tuple[str, ...]:
    parts = split_path(path)
    if not parts or ".".join(parts) != path or any(
            not (p.startswith('"') or re.fullmatch(r"[A-Za-z_][A-Za-z0-9_'-]*", p)) for p in parts):
        die(f"invalid option path {path!r}; use a dotted path such as settings.extractor.base-directory")
    try:
        return tuple(json.loads(p) if p.startswith('"') else p for p in parts)
    except json.JSONDecodeError:
        die(f"invalid quoted attribute in {path!r}")


def assignments(info: dict, specs: list[str]) -> dict[str, object]:
    """Validate relative option names; values are JSON or plain strings, never Nix code."""
    prefix = info["prefix"] + "."
    known = {tuple(json.loads(p) if p.startswith('"') else p for p in split_path(
        o["name"].removeprefix(prefix))): o for o in info["options"]}
    values: dict[tuple[str, ...], object] = {}
    for spec in specs:
        if "=" not in spec:
            die(f"--set needs PATH=VALUE, got {spec!r}")
        path, raw = spec.split("=", 1)
        path = path.removeprefix(info["path"] + ".")
        segments = path_segments(path)
        matches = [(k, o) for k, o in known.items() if len(k) <= len(segments)
                   and all(a == b or a == "<name>" for a, b in zip(k, segments))]
        if not matches:
            hint = " Put application settings under settings." if ("settings",) in known else ""
            die(f"{info['path']}.{path} is not a declared option.{hint} "
                f"See nixmod doc {info['path']} --{info['scope']}.")
        key, option = max(matches, key=lambda match: len(match[0]))
        typ = (option.get("type") or "").lower()
        if len(key) < len(segments) and not any(t in typ for t in (
                "attribute set", "submodule", "json value", "toml value", "yaml value")):
            die(f"{info['path']}.{'.'.join(key)} is a {typ}, not a set of settings")
        for previous in values:
            if previous[:len(segments)] == segments or segments[:len(previous)] == previous:
                die(f"overlapping --set paths: {'.'.join(previous)} and {path}; specify each value once")
        try:
            value = json.loads(raw, parse_constant=lambda constant:
                              die(f"invalid JSON number {constant} for {path}; quote it if you want text"))
        except json.JSONDecodeError:
            if raw.lstrip().startswith(('{', '[', '"')):
                die(f"invalid JSON value for {path}; quote strings or use valid JSON objects/lists")
            value = raw
        values[segments] = value

    result: dict[str, object] = {}
    for segments, value in values.items():
        target = result
        for segment in segments[:-1]:
            target = target.setdefault(segment, {})
        target[segments[-1]] = value
    return result


def example_leaves(value: dict, prefix=(), configured=None) -> list[str]:
    """Keep example assignments inside a live wrapper; no commented outer braces."""
    lines = []
    for key, val in value.items():
        path = prefix + (key,)
        if isinstance(val, dict) and val and "_type" not in val:
            if configured is not None and key in configured and not isinstance(configured[key], dict):
                continue
            lines += example_leaves(val, path, (configured or {}).get(key))
        elif configured is not None and key in configured:
            continue
        else:
            lhs = ".".join(data_attr(k) for k in path)
            lines += f"{lhs} = {to_nix(val)};".splitlines()
    return lines


def option_body(info: dict, ind: str) -> list[str]:
    prefix = info["prefix"] + "."
    rel = {o["name"][len(prefix):]: o for o in info["options"] if o["name"].startswith(prefix)}
    rel = {k: v for k, v in rel.items() if not noise(k)}
    top = sorted((k for k in rel if len(split_path(k)) == 1),
                 key=lambda k: (k != "enable", k != "package", k))
    nested: dict[str, list[str]] = {}
    for k in sorted(rel):
        if len(split_path(k)) > 1:
            nested.setdefault(split_path(k)[0], []).append(k)

    out: list[str] = []
    configured = info.get("assignments", {})
    if "enable" in rel:
        out.append(f"{ind}enable = {to_nix(configured.get('enable', True), literals=False)};")
        top.remove("enable")
    for k in top:
        option = rel[k]
        example = option.get("exampleValue")
        # An empty set preserves the module's default. Examples stay comments:
        # upstream examples may contain credentials or optional services.
        editable = (to_nix(option.get("default")).replace(" ", "") == "{}"
                    and isinstance(example, dict) and "_type" not in example and example)
        if editable and (k not in configured or isinstance(configured[k], dict)):
            out += ["", f"{ind}# {k} — {option.get('type')}"]
            out += [f"{ind}#   {line}" for line in describe(option.get("description"))]
            out += [f"{ind}{attr(k)} = {{"]
            examples = example_leaves(example, configured=configured.get(k))
            if examples:
                out += [f"{ind}  # Upstream example; uncomment the settings you want here."]
                out += [f"{ind}  # {line}" for line in examples]
            else:
                out += [f"{ind}  # Add further application settings here."]
            for key, val in (configured.get(k) or {}).items():
                out += [f"{ind}  {line}" for line in f"{data_attr(key)} = {to_nix(val, literals=False)};".splitlines()]
            out += [f"{ind}}};"]
        elif k in configured:
            out += ["", f"{ind}# {k} — {option.get('type')}"]
            out += [f"{ind}{line}" for line in f"{attr(k)} = {to_nix(configured[k], literals=False)};".splitlines()]
        else:
            out += [""] + render_option(k, option, ind)
    # Some module trees expose only nested options rather than a top-level set.
    for key, val in configured.items():
        if key not in top and key != "enable":
            out += [""] + [f"{ind}{line}" for line in f"{data_attr(key)} = {to_nix(val, literals=False)};".splitlines()]
    for head, keys in nested.items():
        out += ["", f"{ind}# ── {head} " + "─" * max(4, WIDTH - len(ind) - len(head) - 6)]
        for k in keys:
            out += render_option(k, rel[k], ind) + [""]
        out.pop()
    return out


# ── templates ──────────────────────────────────────────────────────────────
# Each returns (header lines after the title, module body) for a module of
# `kind` "home" or "nixos"; `package` returns a whole file instead.

AROUND = {
    "home": """\
# ── around it ───────────────────────────────────────────────────────────
# Packages next to it (CLI helpers, plugins, fonts):
# home.packages = with pkgs; [ ];
#
# A config file the module does not cover, in ~/.config:
# xdg.configFile."{name}/config".text = ''
# '';
#
# Environment for your session:
# home.sessionVariables = {{ EXAMPLE = "1"; }};
#
# Default app for a MIME type:
# xdg.mimeApps.defaultApplications."text/html" = [ "{name}.desktop" ];
#
# A secret (laptop only; sops is not on the generic host):
# sops.secrets."{name}-token" = {{ }};   # path: config.sops.secrets."{name}-token".path""",
    "nixos": """\
# ── around it ───────────────────────────────────────────────────────────
# System packages next to it:
# environment.systemPackages = with pkgs; [ ];
#
# Ports, if it listens:
# networking.firewall.allowedTCPPorts = [ ];
#
# Groups the user needs (devices, sockets):
# users.users.${{user}}.extraGroups = [ "{name}" ];
#
# A file in /etc:
# environment.etc."{name}/config".text = ''
# '';""",
}


def block(text: str, indent: int = 4) -> list[str]:
    return [(" " * indent + l) if l else "" for l in textwrap.dedent(text).strip("\n").splitlines()]


def t_program(name, kind, info):
    pkg, path = info.get("pkg"), info.get("path")
    src = {"home": "home-manager", "nixos": "NixOS"}[kind]
    if path:
        pre = info["prefix"] + "."
        n = len([o for o in info["options"] if not noise(o["name"].removeprefix(pre))])
        head = [f"# From {src}'s {path} ({n} options, as pinned in flake.lock).",
                "# Enable is set; empty settings wrappers are ready to edit. Examples stay commented.",
                "# Keep application settings inside their wrapper. Option docs:",
                f"#   nixmod doc {path} --{kind}"]
        sources = sorted({url for o in info["options"] for url in o.get("sources", [])})
        head += [f"# Module source: {url}" for url in sources]
        body = [f"    {'.'.join(attr(s) for s in path.split('.'))} = {{"] + option_body(info, "      ") + ["    };"]
    else:
        head = [f"# Neither home-manager nor NixOS has programs.{name} / services.{name},",
                "# so this installs the package and lists the usual ways to configure it."]
        lst = "home.packages" if kind == "home" else "environment.systemPackages"
        body = [f"    {lst} = [ pkgs.{name} ];"] if pkg else \
               [f"    # No pkgs.{name}; find the attribute with `nixmod search {name}`, then:",
                f"    # {lst} = [ pkgs.{name} ];"]
    body += [""] + ["    " + l if l else "    #" for l in AROUND[kind].format(name=name).splitlines()]
    cfg = f"cfg = config.{path};" if path else f"# cfg = config.programs.{name};"
    return head, cfg, body


def t_packages(name, kind, info):
    lst = "home.packages" if kind == "home" else "environment.systemPackages"
    first = f"      {name} # TODO: what it is for" if info.get("pkg") else f"      # {name}"
    body = [f"    {lst} = with pkgs; [", first] + block("""
    # ripgrep                     # one per line, with what it is for
    # python3Packages.requests
    # (callPackage ./_NAME/thing.nix { })   # a derivation beside this module
    """, 6) + ["    ];", ""] + block("""
    # Find attribute names: `nixmod search NAME`, or `ns`.
    # Unfree packages are allowed in this flake (nixpkgs.config.allowUnfree).
    # A package from another flake input (add `inputs` to the arguments above):
    #   inputs.zen-browser.packages.${pkgs.stdenv.hostPlatform.system}.default
    """)
    body = [l.replace("_NAME", "_" + name) for l in body]
    return ["# A bundle of packages. One per line, with what it is for."], f"# cfg = config.{lst};", body


def t_script(name, kind, info):
    lst = "home.packages" if kind == "home" else "environment.systemPackages"
    v = re.sub(r"\W", "_", name)
    body = block(f"""
    {lst} = [ {v} ];
    """)
    let = block(f"""
    # `{name}` on PATH. shellcheck runs at build time; a warning fails the build.
    {v} = pkgs.writeShellApplication {{
      name = "{name}";
      # Commands it calls, put on its PATH (no absolute paths needed):
      runtimeInputs = with pkgs; [ coreutils gnugrep jq ];
      # bashOptions = [ "errexit" "nounset" "pipefail" ];   # the default
      # excludeShellChecks = [ "SC2086" ];
      # runtimeEnv = {{ {name.upper().replace('-', '_')}_HOME = "/var/lib/{name}"; }};
      text = ''
        usage() {{ echo "usage: {name} [-h] ARG"; }}
        case "''${{1:-}}" in
          -h|--help) usage; exit 0 ;;
          "") usage >&2; exit 1 ;;
        esac

        echo "{name}: $1"
      '';
    }};

    # The same in Python (flake8 runs at build time; ignore what you must):
    # {v} = pkgs.writers.writePython3Bin "{name}" {{
    #   libraries = with pkgs.python3Packages; [ rich requests ];
    #   flakeIgnore = [ "E501" ];
    # }} ''
    #   import sys
    #   print("{name}:", sys.argv[1:])
    # '';

    # Or keep the script in a file beside this module (modules/…/_{name}/{name}.sh):
    # {v} = pkgs.writeShellApplication {{ name = "{name}"; text = builtins.readFile ./_{name}/{name}.sh; }};
    """, 4)
    return ["# A command of your own, packaged so its dependencies come with it."], let, body


def t_service(name, kind, info):
    if kind == "home":
        body = block(f"""
        systemd.user.services.{name} = {{
          Unit = {{
            Description = "{name}";
            After = [ "network-online.target" ];
            # PartOf = [ "graphical-session.target" ];   # for things that need the desktop
          }};
          Service = {{
            ExecStart = "${{pkgs.hello}}/bin/hello";   # TODO: the command
            # Type = "oneshot";                         # run once (with the timer below)
            Restart = "on-failure";
            RestartSec = 5;
            # Environment = [ "EXAMPLE=1" ];
            # EnvironmentFile = config.sops.secrets."{name}-env".path;   # laptop only
          }};
          Install.WantedBy = [ "default.target" ];   # or graphical-session.target
        }};

        # Run it on a schedule instead of always (set Type = "oneshot" above and
        # drop Install.WantedBy there):
        # systemd.user.timers.{name} = {{
        #   Unit.Description = "{name} schedule";
        #   Timer = {{ OnCalendar = "daily"; Persistent = true; RandomizedDelaySec = "10m"; }};
        #   Install.WantedBy = [ "timers.target" ];
        # }};

        # Logs: journalctl --user -u {name} -f      Restart: systemctl --user restart {name}
        """, 4)
    else:
        body = block(f"""
        systemd.services.{name} = {{
          description = "{name}";
          wantedBy = [ "multi-user.target" ];
          after = [ "network-online.target" ];
          wants = [ "network-online.target" ];
          # path = with pkgs; [ coreutils ];     # PATH for the script
          # environment.EXAMPLE = "1";
          serviceConfig = {{
            ExecStart = "${{pkgs.hello}}/bin/hello";   # TODO: the command
            # Type = "oneshot";
            Restart = "on-failure";
            RestartSec = 5;
            # A throwaway user and a state dir in /var/lib/{name}:
            # DynamicUser = true;
            # StateDirectory = "{name}";
            # Hardening — loosen what it actually needs:
            # ProtectSystem = "strict";
            # ProtectHome = true;
            # PrivateTmp = true;
            # NoNewPrivileges = true;
            # EnvironmentFile = config.sops.secrets."{name}-env".path;   # laptop only
          }};
        }};

        # On a schedule instead of always (Type = "oneshot", drop wantedBy above):
        # systemd.timers.{name} = {{
        #   wantedBy = [ "timers.target" ];
        #   timerConfig = {{ OnCalendar = "daily"; Persistent = true; RandomizedDelaySec = "10m"; }};
        # }};

        # Logs: journalctl -u {name} -f      Restart: sudo systemctl restart {name}
        """, 4)
    return [f"# A hand-written {'user ' if kind == 'home' else ''}systemd service."], \
        f"# cfg = config.systemd.{'user.' if kind == 'home' else ''}services.{name};", body


def t_config(name, kind, info):
    if kind != "home":
        die("the config template is home-manager only; for /etc use -t program or -t feature --nixos")
    body = block(f"""
    # Written into the store, read-only, replaced on every switch:
    xdg.configFile."{name}/config".text = ''
      # {name} settings
    '';

    # From a file beside this module (modules/home/_{name}/config):
    # xdg.configFile."{name}/config".source = ./_{name}/config;
    # A whole directory:
    # xdg.configFile."{name}" = {{ source = ./_{name}; recursive = true; }};

    # Editable in place (the live file is your checkout, like dotfiles.nix):
    # xdg.configFile."{name}/config".source =
    #   config.lib.file.mkOutOfStoreSymlink "${{config.home.homeDirectory}}/NixDaemon/dotfiles/home/.config/{name}/config";

    # Somewhere other than ~/.config:
    # home.file.".{name}rc".text = '' '';
    # home.file.".local/share/{name}/data.json".text = builtins.toJSON {{ key = "value"; }};

    # Generated formats instead of hand-written text:
    # xdg.configFile."{name}/config.toml".source = (pkgs.formats.toml {{ }}).generate "{name}.toml" {{ key = "value"; }};
    # xdg.configFile."{name}/config.json".text = builtins.toJSON {{ key = "value"; }};
    # xdg.configFile."{name}/config.yaml".source = (pkgs.formats.yaml {{ }}).generate "{name}.yaml" {{ }};

    # Run something when the file changes (reload a daemon …):
    # xdg.configFile."{name}/config".onChange = "${{pkgs.procps}}/bin/pkill -USR1 {name} || true";

    # The program itself, if no other module installs it:
    # home.packages = [ pkgs.{name} ];
    """)
    return ["# Config files for something no module configures."], f'# cfg = config.xdg.configFile."{name}/config";', body


def t_feature(name, kind, info):
    lst = "home.packages" if kind == "home" else "environment.systemPackages"
    pkgline = f"package = lib.mkPackageOption pkgs \"{name}\" {{ }};" if info.get("pkg") else \
        f"# package = lib.mkPackageOption pkgs \"{name}\" {{ }};"
    let = f"cfg = config.daemon.{name};"
    body = block(f"""
    options.daemon.{name} = {{
      enable = lib.mkEnableOption "{name}";
      {pkgline}
      # port = lib.mkOption {{
      #   type = lib.types.port;
      #   default = 8080;
      #   description = "Port {name} listens on.";
      # }};
      # extraArgs = lib.mkOption {{
      #   type = with lib.types; listOf str;
      #   default = [ ];
      #   description = "Extra command-line arguments.";
      # }};
      # mode = lib.mkOption {{
      #   type = lib.types.enum [ "fast" "safe" ];
      #   default = "safe";
      #   description = "Which mode.";
      # }};
    }};

    config = lib.mkIf cfg.enable {{
      {'' if info.get('pkg') else '# '}{lst} = [ cfg.package ];
      # assertions = [ {{ assertion = cfg.port != 22; message = "daemon.{name}.port: 22 is ssh"; }} ];
      # Everything this feature turns on goes here; it is all off until
      #   daemon.{name}.enable = true;
      # is set ({'modules/hosts/laptop/configuration.nix' if kind == 'nixos' else 'modules/home/default.nix, beside the imports'}).
    }};
    """)
    return [f"# A switch: daemon.{name}.enable, with typed options. Off until enabled."], let, body


def t_package(name, kind, info):
    return f"""\
{{ ... }}:
{{
  perSystem =
    {{ pkgs, lib, ... }}:
    {{
      # nix build .#{name}   nix run .#{name}
      packages.{name} = pkgs.stdenv.mkDerivation (finalAttrs: {{
        pname = "{name}";
        version = "0.1.0";

        # The first build fails and prints the real hash; paste it here.
        src = pkgs.fetchFromGitHub {{
          owner = "OWNER";
          repo = "{name}";
          rev = "v${{finalAttrs.version}}";
          hash = lib.fakeHash;
        }};
        # src = pkgs.fetchurl {{ url = "https://…/{name}-${{finalAttrs.version}}.tar.gz"; hash = lib.fakeHash; }};
        # src = ./_{name};   # source beside this file

        # nativeBuildInputs = with pkgs; [ cmake pkg-config makeWrapper ];
        # buildInputs = with pkgs; [ openssl ];
        # makeFlags = [ "PREFIX=$(out)" ];
        # installPhase = ''
        #   runHook preInstall
        #   install -Dm755 {name} $out/bin/{name}
        #   runHook postInstall
        # '';

        meta = {{
          description = "TODO";
          homepage = "https://github.com/OWNER/{name}";
          license = lib.licenses.mit;
          mainProgram = "{name}";
          platforms = lib.platforms.linux;
        }};
      }});

      # Other languages, same idea (replace the mkDerivation above):
      #   pkgs.rustPlatform.buildRustPackage {{ pname; version; src; cargoHash = lib.fakeHash; }}
      #   pkgs.buildGoModule {{ pname; version; src; vendorHash = lib.fakeHash; }}
      #   pkgs.python3Packages.buildPythonApplication {{ pname; version; src; pyproject = true;
      #     build-system = [ pkgs.python3Packages.setuptools ]; }}
    }};

  # To install it, in a home module (with `self` in its outer arguments):
  #   home.packages = [ self.packages.${{pkgs.stdenv.hostPlatform.system}}.{name} ];
}}
"""


BUILDERS = {"program": t_program, "packages": t_packages, "script": t_script, "service": t_service,
            "config": t_config, "feature": t_feature}


def file_for(name: str, kind: str, template: str) -> str:
    if template == "package":
        return f"modules/packages/{name}.nix"
    return f"modules/{'home' if kind == 'home' else 'features'}/{name}.nix"


def render(name: str, kind: str, template: str, info: dict) -> str:
    rel = file_for(name, kind, template)
    pkg = info.get("pkg") or {}
    what = (pkg.get("description") or name).rstrip(".")
    today = datetime.date.today().isoformat()
    title = [f"# {rel} — {what}.", "#", f"# {MARK} on {today} (template: {template})."]
    if template == "package":
        return "\n".join(title) + "\n# TODO: say what this is and why it is built here.\n" + t_package(name, kind, info)

    head, let, body = BUILDERS[template](name, kind, info)
    if pkg.get("version"):
        hp = pkg.get("homepage")
        head = head + [f"# Package: pkgs.{name} {pkg['version']}" + (f" — {hp}" if isinstance(hp, str) else "")]
    head.append("# TODO: say here why this is on the machine and anything non-obvious.")
    args = "{ config, lib, pkgs, ... }:" if kind == "home" else "{ config, lib, pkgs, user, ... }:"
    let_lines = let if isinstance(let, list) else [f"    {let}"]
    lines = title + head + [
        "{ ... }:",
        "let theme = import ../_palette.nix; in # the system colours: theme.palette.gold, theme.name …",
        "{",
        f"  flake.{ATTR[kind]}.{name} =",
        f"  {args}",
        "  let",
        "    # Values used more than once below.",
        *let_lines,
        "    # colours = theme.palette;   # base surface text gold pine foam love rose iris …",
        "  in",
        "  {",
        *body,
        "  };",
        "}",
    ]
    return "\n".join(l.rstrip() for l in lines) + "\n"


# ── imports lists ──────────────────────────────────────────────────────────

def import_list(src: str, kind: str):
    """(start, end) of the body of the first `imports = [` naming self.<kind>."""
    m = re.search(r"imports = (with self\.%s; )?\[\n" % ATTR[kind], src)
    if not m:
        return None
    close = re.compile(r"^\s*\]", re.M).search(src, m.end())
    return (m.end(), close.start()) if close else None


def wire(repo: Path, host: str, kind: str, name: str, note: str) -> str | None:
    spec = WIRING.get(host, {}).get(kind)
    if not spec:
        return None
    target, entry = spec[0], spec[1].format(name=name)
    path = repo / target
    src = path.read_text()
    span = import_list(src, kind)
    if not span:
        return None
    entries = [l for l in src[span[0]:span[1]].splitlines() if l.strip() and not l.strip().startswith("#")]
    if entry in (l.split("#")[0].strip() for l in entries):
        return f"{target} (already listed)"
    indent = re.match(r"\s*", entries[-1]).group(0) if entries else "      "
    path.write_text(src[:span[1]] + f"{indent}{entry} # {note}\n" + src[span[1]:])
    return target


def unwire(repo: Path, kind: str, name: str, apply: bool) -> list[str]:
    """Drop `name` from every host's imports list. Returns the files touched."""
    touched = []
    for host, kinds in WIRING.items():
        if kind not in kinds:
            continue
        target, entry = kinds[kind][0], kinds[kind][1].format(name=name)
        path = repo / target
        src = path.read_text()
        span = import_list(src, kind)
        if not span:
            continue
        lines = src[span[0]:span[1]].splitlines(keepends=True)
        kept = [l for l in lines if l.split("#")[0].strip() != entry]
        if len(kept) != len(lines):
            touched.append(target)
            if apply:
                path.write_text(src[:span[0]] + "".join(kept) + src[span[1]:])
    return touched


# ── commands ───────────────────────────────────────────────────────────────

def cmd_new(a, repo: Path) -> None:
    name, template = a.name, a.template
    if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_-]*", name):
        die(f"{name!r} is not usable as a module name; pick one like `my-tool`")
    host = pick_host(repo, a.host)

    if template == "program":
        info = nix_eval(repo, host=host, name=name, scope=a.scope or "auto", want=a.option)
        if a.option and not info["path"]:
            die(f"no option tree {a.option} in {a.scope or 'home-manager or NixOS'}")
        if not info["path"] and not info["pkg"]:
            print(f"nixmod: no programs.{name}/services.{name} module and no pkgs.{name}; "
                  f"writing a bare template (try `nixmod search {name}`)", file=sys.stderr)
        kind = info["scope"] or a.scope or "home"
    else:
        # Only the package metadata is wanted; where it goes is the template's call.
        info = nix_eval(repo, host=host, name=name, mode="pkg") | {"path": None, "options": []}
        kind = a.scope or ("nixos" if template == "feature" else "home")

    if a.set:
        if template != "program" or not info.get("path"):
            die("--set needs a recognized program/service module; use nixmod search NAME to find one")
        info["assignments"] = assignments(info, a.set)

    text = render(name, kind, template, info)
    if a.dry_run:
        sys.stdout.write(text)
        return

    rel = file_for(name, kind, template)
    dest = repo / rel
    pattern = rf"packages\.{re.escape(name)} =" if template == "package" else rf"flake\.{ATTR[kind]}\.{re.escape(name)} ="
    clash = run("grep", "-rlE", pattern, str(repo / "modules")).stdout.split()
    if clash and not (a.force and clash == [str(dest)]):
        die(f"{name} is already declared in {', '.join(clash)}")
    if dest.exists() and not a.force:
        die(f"{rel} exists (use --force to overwrite)")
    dest.parent.mkdir(parents=True, exist_ok=True)
    dest.write_text(text)

    parsed = run("nix-instantiate", "--parse", str(dest))
    if parsed.returncode != 0:
        die(f"wrote {rel} but it does not parse; the file is left for you:\n" + parsed.stderr.strip())
    git_add(repo, rel)

    wired = None
    if template != "package" and not a.no_wire:
        wired = wire(repo, host, kind, name, info.get("path") or f"{template} (nixmod)")
    print(f"wrote   {rel}   [{template}: {info.get('path') or kind}]")
    if template == "package":
        print(f"build   nix build ~/NixDaemon#{name}   (fix src and hash first)")
    else:
        print(f"wired   {wired}" if wired else f"wired   nothing — name `{name}` in an imports list yourself")
    if template == "feature":
        print(f"enable  daemon.{name}.enable = true;   in the host configuration")
    if a.edit:
        editor = os.environ.get("EDITOR") or shutil.which("nvim") or "vi"
        if subprocess.run(shlex.split(editor) + [str(dest)]).returncode != 0:
            die(f"editor failed; {rel} has been kept")
        parsed = run("nix-instantiate", "--parse", str(dest))
        if parsed.returncode != 0:
            die(f"{rel} does not parse after editing:\n" + parsed.stderr.strip())
    if a.check or (template == "program" and wired and not a.no_check):
        if not check_hosts(repo, None if a.check else [host]):
            die(f"configuration failed validation; {rel} has been kept. "
                f"Edit it, then run nixmod check {name} --host {host}")
    elif template == "program":
        print("check   syntax only; host validation skipped" + (" because the module was not wired" if not wired else ""))
    if template != "package":
        print(f"next    after editing: nixmod check {name} --host {host}")
        print("build   nh os build   (nixmod does not activate the system)")


def declared(repo: Path, name: str) -> list[tuple[str, Path]]:
    """[(kind, file)] for every module or package called `name`."""
    found = []
    for kind, pat in (("home", rf"flake\.homeModules\.{name} ="), ("nixos", rf"flake\.nixosModules\.{name} ="),
                      ("package", rf"^\s*packages\.{name} =")):
        for f in run("grep", "-rlE", pat, str(repo / "modules")).stdout.split():
            found.append((kind, Path(f)))
    return found


def cmd_rm(a, repo: Path) -> None:
    name = a.name
    hits = declared(repo, re.escape(name))
    if a.scope:
        hits = [h for h in hits if h[0] == a.scope]
    if not hits:
        die(f"no module or package called {name}")
    if len(hits) > 1:
        die(f"{name} is declared more than once: "
            + ", ".join(f"{k} in {f.relative_to(repo)}" for k, f in hits) + " — pick one with --home / --nixos")
    kind, path = hits[0]
    rel = str(path.relative_to(repo))

    # Never the machine's own definition, whatever --force says.
    if rel.startswith("modules/hosts/") or rel in ("modules/parts.nix", "modules/_palette.nix"):
        die(f"{rel} defines a host; nixmod will not delete it")
    made_by_us = MARK in path.read_text()
    if not made_by_us and not a.force:
        die(f"{rel} was not made by nixmod. If you really mean it: nixmod rm --force {name}")
    decls = re.findall(r"flake\.(?:home|nixos)Modules\.([\w-]+) =|^\s*packages\.([\w-]+) =",
                       path.read_text(), re.M)
    if any((x or y) != name for x, y in decls):
        die(f"{rel} declares more than {name}; edit it by hand")

    wiring = unwire(repo, kind, name, apply=False) if kind != "package" else []
    # Anything else that still names it would break evaluation once it is gone.
    if kind == "package":
        ref = rf"packages\.\$\{{[^}}]*\}}\.{re.escape(name)}\b|self\.packages.*\b{re.escape(name)}\b"
    else:
        ref = rf"self\.{ATTR[kind]}\.{re.escape(name)}\b|\bdaemon\.{re.escape(name)}\."
    users = [l for l in run("grep", "-rnE", ref, str(repo / "modules")).stdout.splitlines()
             if not l.startswith(str(path) + ":")
             and not re.match(r"[^:]*:\d+:\s*#", l)          # a comment only mentions it
             and "/_nixmod/" not in l.split(":")[0]
             and not any(l.startswith(str(repo / w) + ":") and f"self.nixosModules.{name}" in l for w in wiring)]
    sibling = path.parent / f"_{name}"

    print(f"remove  {rel}" + ("" if made_by_us else "   (NOT made by nixmod)"))
    if sibling.is_dir():
        print(f"remove  {sibling.relative_to(repo)}/")
    for w in wiring:
        print(f"unwire  {w}")
    for u in users:
        print(f"STILL   {u.removeprefix(str(repo) + '/')}")
    if users and not a.force:
        die("other files still use it (above); change them first, or --force to delete anyway")
    if a.dry_run:
        return
    if not a.yes:
        if not sys.stdin.isatty():
            die("not a terminal; pass -y to confirm")
        if input("delete? [y/N] ").strip().lower() not in ("y", "yes"):
            die("nothing changed")

    unwire(repo, kind, name, apply=True)
    tracked = (repo / ".git").exists() and run("git", "-C", str(repo), "ls-files", "--error-unmatch", rel).returncode == 0
    if tracked:
        run("git", "-C", str(repo), "rm", "-q", "-f", "--", rel)
    path.unlink(missing_ok=True)
    if sibling.is_dir():
        run("git", "-C", str(repo), "rm", "-q", "-r", "-f", "--", str(sibling.relative_to(repo)))
        shutil.rmtree(sibling, ignore_errors=True)
    for w in wiring:
        if run("nix-instantiate", "--parse", str(repo / w)).returncode != 0:
            die(f"{w} no longer parses after unwiring; restore it with `jj restore {w}`")
    git_add(repo, *wiring)
    print(f"deleted {name}. Undo before committing: jj restore {rel} {' '.join(wiring)}".rstrip())
    if a.check and not check_hosts(repo):
        sys.exit(1)
    print("next    nh os switch   (check first: nh os build)")


def cmd_list(a, repo: Path) -> None:
    mine = run("grep", "-rlF", MARK, str(repo / "modules")).stdout.split()
    mine = [m for m in mine if not m.endswith((".py", "options.nix"))]
    print("made by nixmod:" if mine else "made by nixmod: none yet")
    for f in sorted(mine):
        t = re.search(r"\(template: (\w+)\)", Path(f).read_text())
        print(f"  {Path(f).relative_to(repo)}" + (f"   [{t.group(1)}]" if t else ""))
    print("\ntemplates (nixmod new -t NAME …):")
    for k, v in TEMPLATES.items():
        print(f"  {k:<9} {v}")


def cmd_search(a, repo: Path) -> None:
    r = nix_eval(repo, host=pick_host(repo, a.host), name=a.name, mode="search")
    for m in r["modules"]:
        print(m)
    if r["packages"]:
        print("packages: " + " ".join(r["packages"]))


def cmd_doc(a, repo: Path) -> None:
    info = nix_eval(repo, host=pick_host(repo, a.host), name=a.name, scope=a.scope or "auto",
                    want=a.name if "." in a.name else None)
    if not info["path"]:
        die(f"no option tree {a.name}")
    print(f"{info['scope']}: {info['path']} (pinned in flake.lock)")
    for url in sorted({url for o in info["options"] for url in o.get("sources", [])}):
        print(f"source: {url}")
    print()
    for o in info["options"]:
        rel = o["name"].removeprefix("<name>.")
        if noise(rel):
            continue
        print(f"{rel}  ({o.get('type')})")
        d = o.get("description")
        d = d.get("text") if isinstance(d, dict) else d
        for l in textwrap.wrap(re.sub(r"\s+", " ", d or ""), 74):
            print("    " + l)
        if o.get("default") is not None:
            print("    default: " + to_nix(o["default"]).splitlines()[0])
        if o.get("example") is not None:
            print("    example:")
            print(textwrap.indent(to_nix(o["example"]), "      "))
        print()


def cmd_check(a, repo: Path) -> None:
    if a.name:
        if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_-]*", a.name):
            die("check needs a module name, such as gallery-dl")
        hits = declared(repo, re.escape(a.name))
        if a.scope:
            hits = [hit for hit in hits if hit[0] == a.scope]
        if not hits:
            die(f"no module or package called {a.name}")
        for _, path in hits:
            parsed = run("nix-instantiate", "--parse", str(path))
            if parsed.returncode != 0:
                die(f"{path.relative_to(repo)} does not parse:\n" + parsed.stderr.strip())
            print(f"check   {path.relative_to(repo)}: parses")
        if any(kind == "package" for kind, _ in hits):
            die("package templates need nix build .#NAME; host evaluation does not check their build")
    if not check_hosts(repo, [pick_host(repo, a.host)]):
        sys.exit(1)


def main() -> None:
    argv = sys.argv[1:]
    if argv and argv[0] not in COMMANDS and argv[0] not in ("-h", "--help"):
        argv = ["new"] + argv  # `nixmod firefox` is `nixmod new firefox`

    ap = argparse.ArgumentParser(prog="nixmod", formatter_class=argparse.RawDescriptionHelpFormatter,
                                 description=__doc__.split("\n\n")[0], epilog="\n\n".join(__doc__.split("\n\n")[1:]))
    sub = ap.add_subparsers(dest="cmd", required=True)

    def common(p, scope=True):
        if scope:
            g = p.add_mutually_exclusive_group()
            g.add_argument("--home", dest="scope", action="store_const", const="home", help="home-manager")
            g.add_argument("--nixos", dest="scope", action="store_const", const="nixos", help="NixOS")
        p.add_argument("--host", help="nixosConfigurations to use (default: this hostname, or the sole host)")
        p.add_argument("--repo", help="the checkout (default: $NIXDAEMON, the git root, ~/NixDaemon)")

    p = sub.add_parser("new", help="write a module from a template")
    p.add_argument("name", help="the program / module name")
    p.add_argument("-t", "--template", choices=list(TEMPLATES) , default="program",
                   help="what kind of module (see `nixmod templates`)")
    p.add_argument("--option", metavar="PATH", help="program template: the option tree, e.g. services.syncthing")
    p.add_argument("--set", action="append", default=[], metavar="PATH=VALUE",
                   help="set a relative option (repeatable); VALUE is JSON or a plain string")
    p.add_argument("-n", "--dry-run", action="store_true", help="print the file, write nothing")
    p.add_argument("--no-wire", action="store_true", help="do not add it to the host's imports")
    p.add_argument("-f", "--force", action="store_true", help="overwrite a file of the same name")
    p.add_argument("-e", "--edit", action="store_true", help="open it in $EDITOR afterwards")
    checking = p.add_mutually_exclusive_group()
    checking.add_argument("--check", action="store_true", help="evaluate both hosts (programs check the selected host by default)")
    checking.add_argument("--no-check", action="store_true", help="skip automatic host evaluation; still check syntax")
    common(p)

    p = sub.add_parser("rm", help="delete a module: file, import lines, git")
    p.add_argument("name")
    p.add_argument("-n", "--dry-run", action="store_true", help="show what would go, change nothing")
    p.add_argument("-y", "--yes", action="store_true", help="do not ask")
    p.add_argument("-f", "--force", action="store_true",
                   help="also delete modules nixmod did not make, or that others still use")
    p.add_argument("--check", action="store_true", help="evaluate both hosts afterwards")
    common(p)

    p = sub.add_parser("list", help="modules nixmod made, and the templates")
    common(p, scope=False)
    p = sub.add_parser("templates", help="the templates")
    common(p, scope=False)
    p = sub.add_parser("search", help="programs.* / services.* / packages matching NAME")
    p.add_argument("name")
    common(p, scope=False)
    p = sub.add_parser("doc", help="every option of an option tree")
    p.add_argument("name", metavar="PATH")
    common(p)
    p = sub.add_parser("check", help="check an edited module and evaluate the selected host, without building or activating")
    p.add_argument("name", nargs="?", help="module to check for syntax first (optional)")
    common(p)

    a = ap.parse_args(argv)
    if a.cmd == "templates":
        for k, v in TEMPLATES.items():
            print(f"{k:<9} {v}")
        return
    repo = find_repo(a.repo)
    {"new": cmd_new, "rm": cmd_rm, "list": cmd_list, "search": cmd_search, "doc": cmd_doc,
     "check": cmd_check}[a.cmd](a, repo)


if __name__ == "__main__":
    main()