aboutsummaryrefslogtreecommitdiff
path: root/vps-configuration.env.nix
blob: d5a7f54af767fd2303de01eac49e6b994ba2e2aa (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
{ config, pkgs, ... }:

let
  envsubstConfiguration = {
    TLD = "$TLD";
    nextcloudTLD = "$NEXTCLOUD_TLD";
    gitTLD = "$GIT_TLD";
    prosodyTLD = "$PROSODY_TLD";
    bonecoTLD = "$BONECO_TLD";
    pdfsTLD = "$PDFS_TLD";
    ciLogsTLD = "$CI_LOGS_TLD";
    songbooksDocumentationTLD = "$SONGBOOKS_DOCUMENTATION_TLD";
    piresDocumentationTLD = "$PIRES_DOCUMENTATION_TLD";
    mediatorDocumentationTLD = "$MEDIATOR_DOCUMENTATION_TLD";
    cementDocumentationTLD = "$CEMENT_DOCUMENTATION_TLD";
    piresProdTLD = "$PIRES_PROD_TLD";
    piresProdPort = "$PIRES_PROD_PORT";
    piresProdDir = "$PIRES_PROD_DIR";
    letsencryptEmail = "$LETSENCRYPT_EMAIL";
    authorizedKey = "$AUTHORIZED_KEY";
    userPassword = "$USER_PASSWORD";
    userName = "$USER_NAME";
    dataRoot = "$DATA_ROOT";
    staticRoot = "$STATIC_ROOT";
    ciLogsRoot = "$CI_LOGS_ROOT";
    faviconsRoot = "$FAVICONS_ROOT";
    nextcloudDatabaseUser = "$NEXTCLOUD_DATABASE_USER";
    nextcloudDatabasePassword = "$NEXTCLOUD_DATABASE_PASSWORD";
    nextcloudAdminUser = "$NEXTCLOUD_ADMIN_USER";
    nextcloudAdminPassword = "$NEXTCLOUD_ADMIN_PASSWORD";
    nextcloudTablePrefix = "$NEXTCLOUD_TABLE_PREFIX";
    gitPort = "$GIT_PORT";
    gitRoot = "$GIT_ROOT";
    systemStateVersion = "$SYSTEM_STATE_VERSION";
    prosodyConverseTLD = "$PROSODY_CONVERSE_TLD";
    prosodyAdminUser = "$PROSODY_ADMIN_USER";
    prosodyMUCTLD = "$PROSODY_MUC_TLD";
    prosodyPort = "$PROSODY_PORT";
    prosodyHTTPPort = "$PROSODY_HTTP_PORT";
    prosodyEnable = $PROSODY_ENABLE;
  };
  staticSiteFromRepo = repoName:
    pkgs.stdenv.mkDerivation {
      name = repoName;
      src = fetchTarball
        "https://git.sr.ht/~euandreh/${DOLLAR}{repoName}/archive/master.tar.gz";
      phases = "unpackPhase buildPhase";
      buildPhase = ''
        mkdir ${DOLLAR}out
        cp index.html ${DOLLAR}out
        cp favicon.ico ${DOLLAR}out
      '';
    };
  pkgsUnstable = import (builtins.fetchTarball {
    url = "https://github.com/NixOS/nixpkgs/archive/nixos-unstable.tar.gz";
  }) { };
  piresProd = pkgs.writeShellScriptBin "run-pires.sh" ''
    export FLASK_CONFIG=production

    export PIRES_PROD_DIR="$"
    if [[ ! -d ${envsubstConfiguration.piresProdDir} ]]; then
      ${pkgs.git}/bin/git clone https://gitlab.com/EuAndreh/pires.git ${envsubstConfiguration.piresProdDir}
    fi
    pushd ${envsubstConfiguration.piresProdDir}
    ${pkgs.git}/bin/git pull
    ${pkgsUnstable.poetry}/bin/poetry install --no-dev --extras "waitress"
    ${pkgsUnstable.poetry}/bin/poetry run flask inicializar-banco
    ${pkgsUnstable.poetry}/bin/poetry run waitress-serve --host localhost --port ${envsubstConfiguration.piresProdPort} --call pires:create_app
  '';
in {
  nix = {
    binaryCaches = [ "https://euandreh.cachix.org" ];
    binaryCachePublicKeys =
      [ "euandreh.cachix.org-1:ms8eOKJJtb20GJDPCf8Nvob8YI0oF8dREAMdx3XF/90=" ];
  };

  imports = [ ./hardware-configuration.nix ];

  boot.loader.grub = {
    enable = true;
    version = 2;
    device = "/dev/vda";
  };

  networking = {
    useDHCP = false;
    interfaces.ens3.useDHCP = true;
  };

  environment.systemPackages = with pkgs; [
    vim
    git
    gitAndTools.git-annex
    gotop
  ];

  networking.firewall.allowedTCPPorts = [
    # SSH: OpenSSH
    22

    # HTTP and HTPPS: NGINX
    80
    443
  ] ++ (if prosodyEnable then
    [
      # XMPP: Prosody
      # https://prosody.im/doc/ports
      5000
      5222
      5269
      5280
      5281
      5347
      5582
    ] else []);

  security.acme = {
    acceptTerms = true;
    email = envsubstConfiguration.letsencryptEmail;
  };

  services = {
    openssh = {
      enable = true;
      permitRootLogin = "no";
      passwordAuthentication = false;
    };

    nginx = {
      enable = true;
      recommendedGzipSettings = true;
      recommendedOptimisation = true;
      recommendedProxySettings = true;
      recommendedTlsSettings = true;
      virtualHosts = {
        "${envsubstConfiguration.nextcloudTLD}" = {
          forceSSL = true;
          enableACME = true;
        };
        "${envsubstConfiguration.gitTLD}" = {
          forceSSL = true;
          enableACME = true;
          extraConfig = ''
            location = /favicon.ico {
                    alias ${envsubstConfiguration.dataRoot}/favicons/git.ico;
            }
            location / {
                    proxy_pass http://localhost:${envsubstConfiguration.gitPort};
            }
          '';
        };
        "${envsubstConfiguration.bonecoTLD}" = {
          forceSSL = true;
          enableACME = true;
          root = staticSiteFromRepo "boneco";
        };
        "${envsubstConfiguration.pdfsTLD}" = {
          forceSSL = true;
          enableACME = true;
          root = staticSiteFromRepo "pdfs-da-d-maria";
        };
        "${envsubstConfiguration.ciLogsTLD}" = {
          forceSSL = true;
          enableACME = true;
          root = "${envsubstConfiguration.ciLogsRoot}";
        };
        "${envsubstConfiguration.mediatorDocumentationTLD}" = {
          forceSSL = true;
          enableACME = true;
          extraConfig = ''
            location = / {
                    return 301 master/;
            }
            root ${envsubstConfiguration.staticRoot}/mediator/;
          '';
        };
        "${envsubstConfiguration.cementDocumentationTLD}" = {
          forceSSL = true;
          enableACME = true;
          extraConfig = ''
            location = / {
                    return 301 master/;
            }
            root ${envsubstConfiguration.staticRoot}/cement/;
          '';
        };
        "${envsubstConfiguration.songbooksDocumentationTLD}" = {
          forceSSL = true;
          enableACME = true;
          extraConfig = ''
            location = / {
                    return 301 en/master/;
            }
            root ${envsubstConfiguration.staticRoot}/songbooks/;
          '';
        };
        "${envsubstConfiguration.piresDocumentationTLD}" = {
          forceSSL = true;
          enableACME = true;
          root = "${envsubstConfiguration.staticRoot}/pires/";
        };
        "${envsubstConfiguration.piresProdTLD}" = {
          forceSSL = true;
          enableACME = true;
          locations = {
            "/" = {
              proxyPass =
                "http://localhost:${envsubstConfiguration.piresProdPort}/";
            };
          };
        };
        # Generate and maintain TLS certificate with NGINX
        # to be used by Prosody
        "${envsubstConfiguration.prosodyTLD}" = {
          forceSSL = true;
          enableACME = true;
        };
        "${envsubstConfiguration.prosodyConverseTLD}" = {
          forceSSL = true;
          enableACME = true;
          extraConfig = ''
            location = /favicon.ico {
                    alias ${envsubstConfiguration.dataRoot}/favicons/conversejs.ico;
            }
            location = / {
                    return 301 conversejs;
            }
            location / {
                    proxy_pass http://localhost:${envsubstConfiguration.prosodyHTTPPort}/;
            }
          '';
        };
      };
    };

    postgresql = {
      enable = true;
      ensureDatabases = [ "nextcloud" ];
      package = pkgs.postgresql_11;
      ensureUsers = [{
        name = "nextcloud";
        ensurePermissions."DATABASE nextcloud" = "ALL PRIVILEGES";
      }];
    };

    nextcloud = {
      enable = true;
      package = pkgs.nextcloud19;
      nginx.enable = true;
      hostName = envsubstConfiguration.nextcloudTLD;
      https = true;
      maxUploadSize = "4G";
      autoUpdateApps.enable = true;
      config = {
        overwriteProtocol = "https";
        dbtype = "pgsql";
        dbhost = "/run/postgresql";
        dbuser = envsubstConfiguration.nextcloudDatabaseUser;
        dbpass = envsubstConfiguration.nextcloudDatabasePassword;
        dbtableprefix = envsubstConfiguration.nextcloudTablePrefix;
        adminuser = envsubstConfiguration.nextcloudAdminUser;
        adminpass = envsubstConfiguration.nextcloudAdminPassword;
      };
    };

    prosody = let
      XMPP = {
        fullchainPEM =
          "/var/lib/acme/${envsubstConfiguration.prosodyTLD}/fullchain.pem";
        keyPEM = "/var/lib/acme/${envsubstConfiguration.prosodyTLD}/key.pem";
      };
      ConverseJS = {
        fullchainPEM =
          "/var/lib/acme/${envsubstConfiguration.prosodyConverseTLD}/fullchain.pem";
        keyPEM =
          "/var/lib/acme/${envsubstConfiguration.prosodyConverseTLD}/key.pem";
      };
    in {
      enable = prosodyEnable;
      admins = [ envsubstConfiguration.prosodyAdminUser ];
      allowRegistration = false;
      modules = { websocket = true; };
      package = pkgs.prosody.override {
        withCommunityModules = [ "http_upload" "conversejs" "bookmarks" ];
      };
      extraModules = [ "http_upload" "conversejs" "bookmarks" ];
      virtualHosts = {
        "${envsubstConfiguration.prosodyTLD}" = {
          enabled = true;
          domain = "${envsubstConfiguration.prosodyTLD}";
          ssl = {
            cert = XMPP.fullchainPEM;
            key = XMPP.keyPEM;
          };
        };
        "${envsubstConfiguration.prosodyConverseTLD}" = {
          enabled = true;
          domain = "${envsubstConfiguration.prosodyConverseTLD}";
          ssl = {
            cert = ConverseJS.fullchainPEM;
            key = ConverseJS.keyPEM;
          };
        };
      };
    };

    lighttpd = {
      enable = true;
      port = pkgs.lib.toInt envsubstConfiguration.gitPort;
      cgit = {
        enable = true;
        subdir = "";
        configText = ''
          enable-blame=1
          enable-commit-graph=1
          enable-follow-links=1
          enable-index-owner=0
          enable-log-filecount=1
          enable-log-linecount=1
          root-desc=public repositories
          root-readme=${envsubstConfiguration.gitRoot}/about.html
          readme=:README.md
          readme=:README
          readme=:README.rst
          readme=:README.org
          max-repodesc-length=120
          remove-suffix=1
          root-title=EuAndreh's git repositories
          snapshots=tar.gz zip
          source-filter=${pkgs.cgit}/lib/cgit/filters/syntax-highlighting.py
          about-filter=${pkgs.cgit}/lib/cgit/filters/about-formatting.sh
          scan-path=${envsubstConfiguration.gitRoot}
        '';
      };
    };

    logrotate = {
      enable =
        false; # disabled due to extraConfig not being yet out of unstable
      # extraConfig = ''
      #   compress

      #   ${envsubstConfiguration.ciLogsRoot}/*/*.log {
      #     rotate 5
      #     daily
      #     olddir ${envsubstConfiguration.staticRoot}/logrorate/
      #     createolddir 744 andreh users
      #     su andreh users
      #   }
      # '';
    };
  };

  systemd.services = {
    "nextcloud-setup" = {
      requires = [ "postgresql.service" ];
      after = [ "postgresql.service" ];
    };
    "data-folder-init" = {
      enable = true;
      description = "Setup data folders and permissions";
      wantedBy = [ "multi-user.target" ];
      script = pkgs.lib.fold (p: acc:
        acc + ''
          mkdir -p ${DOLLAR}{p}
          chown -R andreh:users ${DOLLAR}{p}
          chmod -R 755 ${DOLLAR}{p}
        '') "" (with envsubstConfiguration; [
          staticRoot
          gitRoot
          faviconsRoot
          ciLogsRoot
          dataRoot
        ]);
      serviceConfig = { Type = "oneshot"; };
    };
    "poor-mans-logrotate" = {
      enable = true;
      description = "Delete old CI log files";
      wantedBy = [ "multi-user.target" ];
      script = ''
        pushd ${envsubstConfiguration.ciLogsRoot}
        find . -type f -name '*.log' -mtime 1 -delete
        find . -type d -empty -delete
        ${pkgs.bash}/bin/bash ci-gen-index.sh
      '';
      serviceConfig = { Type = "oneshot"; };
    };
    "pires-prod" = {
      enable = true;
      # Unit
      description = "Service for pires server deployment";
      after = [ "network.target" ];
      # Service
      serviceConfig = {
        User = "${envsubstConfiguration.userName}";
        ExecStart = "${DOLLAR}{piresProd}/bin/run-pires.sh";
        Restart = "always";
      };
      # Install
      wantedBy = [ "multi-user.target" ];
    };
  };

  users.extraUsers."${envsubstConfiguration.userName}" = {
    uid = 1000;
    isNormalUser = true;
    extraGroups = [ "wheel" ];
    password = envsubstConfiguration.userPassword;
    openssh.authorizedKeys.keys = [ envsubstConfiguration.authorizedKey ];
  };

  system.stateVersion = envsubstConfiguration.systemStateVersion;
}