#!/usr/bin/env bash # Apply Kontra additions to /etc/nixos/configuration.nix on .13, then rebuild. # Run as: sudo bash patch-kontra-nix.sh set -euo pipefail CFG=/etc/nixos/configuration.nix BAK=$CFG.bak-kontra-$(date +%Y%m%d-%H%M%S) cp -a "$CFG" "$BAK" echo "backup: $BAK" python3 - "$CFG" <<'PYEOF' import sys, io path = sys.argv[1] src = open(path).read() # --- 1) Caddy extraConfig: append reverse_proxy block before the closing `'';` caddy_add = ''' http://kontra.lab.audasmedia.com.au:8000 { reverse_proxy localhost:8600 } http://admin.kontra.lab.audasmedia.com.au:8000 { reverse_proxy localhost:8600 } http://kontra.home.lab:8000 { reverse_proxy localhost:8600 } ''' # The extraConfig string ends with '\n '';' (line 77). Insert before that. needle = "\n '';" i = src.rindex(needle, 0, src.index("services.caddy")) src = src[:i] + caddy_add + needle + src[i+len(needle):] # --- 2) systemd services + timer: insert after the services.caddy attr close (line 79) services_add = ''' # --- KONTRA (GOTH news-opinion site) --- systemd.services.kontra = { description = "Kontra GOTH news-opinion site"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; wantedBy = [ "multi-user.target" ]; serviceConfig = { Type = "simple"; User = "sam"; Group = "users"; WorkingDirectory = "/var/www/kontra_day"; Environment = [ "KONTRA_CONTENT=/var/www/kontra_day/content" "KONTRA_MEDIA=/media" "PORT=8600" ]; ExecStart = "/var/www/kontra_day/bin/kontra-bin"; Restart = "on-failure"; RestartSec = "3"; NoNewPrivileges = true; }; }; systemd.services.kontra-pull = { description = "Pull Kontra content from Gitea (every 30s timer)"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; serviceConfig = { Type = "oneshot"; ExecStart = "/bin/bash /var/www/kontra_day/bin/kontra-pull.sh"; }; }; systemd.timers.kontra-pull = { description = "Kontra content pull timer (30s)"; wantedBy = [ "timers.target" ]; timerConfig = { OnBootSec = "30s"; OnUnitActiveSec = "30s"; AccuracySec = "2s"; }; }; ''' # Insert after the services.caddy closing "};" (line 79). Find "};" following services.caddy. anchor = "services.caddy" idx = src.index(anchor) close = src.find("};", idx) close2 = src.find("};", close + 2) # services attr closes with one more "};"? see structure # The caddy attr is " services.caddy = {\n ... \n '';\n};" -- one close. Insert after it. insert_at = close + 2 src = src[:insert_at] + "\n" + services_add + src[insert_at:] open(path, "w").write(src) print("patched configuration.nix") PY echo "== sanity: syntax check ==" nix-instantiate --parse "$CFG" >/dev/null && echo "Nix syntax OK" || { echo "NIX SYNTAX FAILED — restoring backup"; cp -a "$BAK" "$CFG"; exit 1; } echo "== nixos-rebuild switch (this may take a while) ==" nixos-rebuild switch --show-trace 2>&1 | tail -30 echo "DONE"