{ pkgs, lib, config, ... }:
let
  inherit (lib) types;
  inherit (config) networking;
  cfg = config.install.ssh-nixos;
  nixRunDefaultCommand = "bash";
in
{
options.install.ssh-nixos = {
  PATH = lib.mkOption {
    type = types.listOf types.package;
    default = [];
    apply = lib.makeBinPath;
  };
  script = lib.mkOption {
    type = types.lines;
    default = "";
    apply = script: pkgs.writeShellScriptBin nixRunDefaultCommand ''
      set -eu
      PATH="$PATH:${cfg.PATH}"
      set -x
      ${script}
    '';
  };
  target = lib.mkOption {
    type = types.str;
    default = "root@${networking.hostName}.${networking.domain}";
  };
  profile = lib.mkOption {
    type = types.str;
    default = "/nix/var/nix/profiles/system";
  };
};
config = {
  install.ssh-nixos.PATH = with pkgs; [nix openssh];
  install.ssh-nixos.script =
    let nixos = config.system.build.toplevel; in ''
    nix ''${TRACE:+-L} copy \
     --to ssh://${cfg.target} --substitute-on-destination \
     ${nixos}
    ssh ${cfg.target} nix-env --profile "${cfg.profile}" --set "${nixos}" \
     '&&' "${cfg.profile}"/bin/switch-to-configuration "''${switch:-switch}"
  '';
};
meta.maintainers = [ lib.maintainers.julm ];
}