summaryrefslogtreecommitdiffstats
path: root/krops.nix
blob: 81445ad8728638f2b9bf5bced62f9809ee30ad38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# NAME
#   krops.nix - deployment entry point
#
# SYNOPSIS
#   $(nix-build krops.nix --no-out-link --argstr name HOSTNAME -A deploy)
#
{ lib ? import ~/sync/src/krops/lib
, pkgs ? import ~/sync/src/krops/pkgs {}
, name
, target ? null
}: rec {

  target = "root@${name}.r/var/src";

  source = lib.evalSource [
    {
      hrm.file = {
        path = toString ~/sync/src/hrm;
      };
      nixos-config.symlink = {
        target = "hrm/systems/${name}/config.nix";
      };
      nixpkgs.git = {
        ref = (lib.importJSON ./nixpkgs.json)."nixos-26.05".rev;
        url = "https://github.com/NixOS/nixpkgs";
      };
      secrets.passage = {
        age = "${pkgs.rage}/bin/rage";
        dir = toString ~/sync/secrets/${name};
        identities_file = toString ~/.passage/identities;
      };
      stockholm.file = {
        path = toString ~/sync/src/stockholm;
      };
    }
  ];

  deploy = hrm.legacy.deploy;

  hrm.legacy.deploy = mkAction "legacy" "deploy";
  hrm.flake.deploy = mkAction "flake" "deploy";

  mkAction = build-method: deploy-action: let
    target' = lib.mkTarget target;
    name' = "${name}-deploy-${build-method}-${deploy-action}";
  in
    pkgs.writers.writeDash name' /* sh */ ''
      set -efu
      ${pkgs.populate { source = source; target = target'; }}
      ${pkgs.krops.runShell target' { allocateTTY = true; } /* sh */ ''
        set -efu
        system=$(
          export NIX_PATH=${lib.escapeShellArg target'.path}
          ${builtins.getAttr build-method {
            legacy = /* sh */ ''
              nix-build \
                  -j 1 \
                  --show-trace \
                  --attr nixosConfigurations.${name}.config.system.build.toplevel \
                  '<hrm/legacy.nix>'
            '';
            flake = /* sh */ ''
              nix build \
                  --print-build-logs \
                  --show-trace \
                  --print-out-paths \
                  "$NIX_PATH"/hrm#nixosConfigurations.${name}.config.system.build.toplevel
            '';
          }}
        )
        ${builtins.getAttr deploy-action {
          deploy = /* sh */ ''
            old_gen=$(readlink -f /nix/var/nix/profiles/system)
            new_gen=$(readlink -f "$system")
            if [ "x$old_gen" != "x$new_gen" ]; then
              nix-env -p /nix/var/nix/profiles/system --set "$system"
              "$system"/bin/switch-to-configuration switch
            else
              echo 'Configuration is already up to date' >&2
            fi
          '';
        }}
      ''}
    '';
}