summary refs log tree commit diff
path: root/nixos/modules/services/misc/sourcehut/service.nix
blob: 65b4ad020f9a66d5055158d62a5b44ac6a2f5d6a (plain) (blame)
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
{ config, pkgs, lib }:
serviceCfg: serviceDrv: iniKey: attrs:
let
  cfg = config.services.sourcehut;
  cfgIni = cfg.settings."${iniKey}";
  pgSuperUser = config.services.postgresql.superUser;

  setupDB = pkgs.writeScript "${serviceDrv.pname}-gen-db" ''
    #! ${cfg.python}/bin/python
    from ${serviceDrv.pname}.app import db
    db.create()
  '';
in
with serviceCfg; with lib; recursiveUpdate
{
  environment.HOME = statePath;
  path = [ config.services.postgresql.package ] ++ (attrs.path or [ ]);
  restartTriggers = [ config.environment.etc."sr.ht/config.ini".source ];
  serviceConfig = {
    Type = "simple";
    User = user;
    Group = user;
    Restart = "always";
    WorkingDirectory = statePath;
  } // (if (cfg.statePath == "/var/lib/sourcehut/${serviceDrv.pname}") then {
          StateDirectory = [ "sourcehut/${serviceDrv.pname}" ];
        } else {})
  ;

  preStart = ''
    if ! test -e ${statePath}/db; then
      # Setup the initial database
      ${setupDB}

      # Set the initial state of the database for future database upgrades
      if test -e ${cfg.python}/bin/${serviceDrv.pname}-migrate; then
        # Run alembic stamp head once to tell alembic the schema is up-to-date
        ${cfg.python}/bin/${serviceDrv.pname}-migrate stamp head
      fi

      printf "%s" "${serviceDrv.version}" > ${statePath}/db
    fi

    # Update copy of each users' profile to the latest
    # See https://lists.sr.ht/~sircmpwn/sr.ht-admins/<20190302181207.GA13778%40cirno.my.domain>
    if ! test -e ${statePath}/webhook; then
      # Update ${iniKey}'s users' profile copy to the latest
      ${cfg.python}/bin/srht-update-profiles ${iniKey}

      touch ${statePath}/webhook
    fi

    ${optionalString (builtins.hasAttr "migrate-on-upgrade" cfgIni && cfgIni.migrate-on-upgrade == "yes") ''
      if [ "$(cat ${statePath}/db)" != "${serviceDrv.version}" ]; then
        # Manage schema migrations using alembic
        ${cfg.python}/bin/${serviceDrv.pname}-migrate -a upgrade head

        # Mark down current package version
        printf "%s" "${serviceDrv.version}" > ${statePath}/db
      fi
    ''}

    ${attrs.preStart or ""}
  '';
}
  (builtins.removeAttrs attrs [ "path" "preStart" ])