{ config, lib, pkgs, pkgs-unstable, artifacts, ... }:
{
  cultguard-chromium-pin = pkgs.writeShellApplication {
    name = "cultguard-chromium-pin";
    runtimeInputs = with pkgs; [
      coreutils
      git
      home-manager
      nix
      python3
      systemd
    ];
    text = ''
      set -euo pipefail

      flake_dir="''${DOTFILES_HOME_MANAGER_DIR:-${config.home.homeDirectory}/dotfiles/.config/home-manager}"
      flake_file="$flake_dir/flake.nix"
      default_chromium_ref="''${CULTGUARD_CHROMIUM_DEFAULT_FLAKE:-git+https://github.com/cultscale/cultguard-chromium.git}"
      restart_units=(
        ${lib.escapeShellArg artifacts.serviceUnits.privacyDesktop1}
        ${lib.escapeShellArg artifacts.serviceUnits.privacyDesktop2}
        ${lib.escapeShellArg artifacts.serviceUnits.privacyDesktop3}
        ${lib.escapeShellArg artifacts.serviceUnits.privacyDesktop4}
      )

      log() {
        printf '[cultguard-chromium-pin] %s\n' "$*" >&2
      }

      die() {
        log "error: $*"
        exit 1
      }

      usage() {
        cat <<EOF
Usage:
  cultguard-chromium-pin [--no-switch] [--no-restart] [cultguard-chrome-path-or-flake-ref]

Defaults:
  cultguard-chrome-path-or-flake-ref defaults to $default_chromium_ref
  DOTFILES_HOME_MANAGER_DIR can override the flake checkout path

Note:
  This now repins the privacy desktop Chromium builds only.
EOF
      }

      no_switch=0
      no_restart=0
      target_arg=

      while [[ "$#" -gt 0 ]]; do
        case "$1" in
          --no-switch)
            no_switch=1
            ;;
          --no-restart)
            no_restart=1
            ;;
          -h|--help)
            usage
            exit 0
            ;;
          --*)
            die "unknown option: $1"
            ;;
          *)
            if [[ -n "$target_arg" ]]; then
              die "expected at most one Cultguard Chrome checkout path or flake ref"
            fi
            target_arg="$1"
            ;;
        esac
        shift
      done

      target_arg="''${target_arg:-$default_chromium_ref}"

      [[ -d "$flake_dir" ]] || die "home-manager flake directory not found: $flake_dir"
      [[ -f "$flake_file" ]] || die "home-manager flake file not found: $flake_file"

      resolve_target_ref() {
        local candidate="$1"
        local resolved=""

        if [[ "$candidate" == path:* ]]; then
          resolved="$(realpath -e "$(printf '%s' "$candidate" | cut -c6-)")"
          [[ -d "$resolved" && -f "$resolved/flake.nix" ]] || die "expected a flake checkout at $resolved"
          printf 'path:%s\n' "$resolved"
          return 0
        fi

        if [[ -e "$candidate" ]]; then
          resolved="$(realpath -e "$candidate")"
          if [[ -f "$resolved" && "$(basename "$resolved")" == "flake.nix" ]]; then
            resolved="$(dirname "$resolved")"
          fi
          [[ -d "$resolved" && -f "$resolved/flake.nix" ]] || die "expected a cultguard-chrome checkout with flake.nix, got: $resolved"
          printf 'path:%s\n' "$resolved"
          return 0
        fi

        printf '%s\n' "$candidate"
      }

      target_ref="$(resolve_target_ref "$target_arg")"
      nix eval --raw "$target_ref#browser.name" >/dev/null 2>&1 \
        || die "expected a Cultguard Chrome flake exposing #browser, got: $target_ref"

      python3 - "$flake_file" "$target_ref" <<'PY'
import pathlib
import re
import sys

flake_file = pathlib.Path(sys.argv[1])
target_ref = sys.argv[2]
text = flake_file.read_text()
pattern = re.compile(
    r'(cultguard-chromium\s*=\s*\{\s*url\s*=\s*")[^"]+(";\s*\};)',
    re.S,
)
updated, count = pattern.subn(r'\1' + target_ref + r'\2', text, count=1)
if count != 1:
    raise SystemExit(f"failed to update cultguard-chromium input in {flake_file}")
flake_file.write_text(updated)
PY

      (
        cd "$flake_dir"
        nix flake update cultguard-chromium
      )

      if [[ "$no_switch" -eq 0 ]]; then
        home-manager switch --flake "$flake_dir#mnm"
        if [[ "$no_restart" -eq 0 ]]; then
          systemctl --user restart "''${restart_units[@]}"
        fi
      fi

      printf 'Pinned cultguard-chromium to %s\n' "$target_ref"
      if [[ "$no_switch" -eq 0 ]]; then
        printf 'Applied home-manager switch for %s#mnm\n' "$flake_dir"
        if [[ "$no_restart" -eq 0 ]]; then
          printf 'Restarted privacy browser units: %s\n' "''${restart_units[*]}"
        fi
      else
        printf 'Skipped home-manager switch (--no-switch).\n'
      fi
    '';
  };
}
