@@ -0,0 +1,90 @@
1+{ config, lib, pkgs, utils, ... }:
2+with lib;
3+let
4+ name = "Ubiquiti mFi Controller";
5+ cfg = config.services.mfi;
6+ stateDir = "/var/lib/mfi";
7+ # XXX 2 runtime exceptions using jre8: JSPException on GET / ; can't initialize ./data/keystore on first run.
8+ cmd = "@${pkgs.jre7}/bin/java java -jar ${stateDir}/lib/ace.jar";
9+ mountPoints = [
10+ { what = "${pkgs.mfi}/dl"; where = "${stateDir}/dl"; }
11+ { what = "${pkgs.mfi}/lib"; where = "${stateDir}/lib"; }
12+ { what = "${pkgs.mongodb248}/bin"; where = "${stateDir}/bin"; }
13+ ];
14+ systemdMountPoints = map (m: "${utils.escapeSystemdPath m.where}.mount") mountPoints;
15+ ports = [ 6080 6880 6443 6843 ];
16+in
17+{
18+ options = {
19+ services.mfi = {
20+ enable = mkEnableOption name;
21+ openPorts = mkOption {
22+ type = types.bool;
23+ default = true;
24+ description = "Whether to open TCP ports ${concatMapStrings (a: "${toString a} ") ports}for the services.";
25+ };
26+ };
27+ };
28+
29+ config = mkIf cfg.enable {
30+
31+ networking.firewall.allowedTCPPorts = mkIf config.services.mfi.openPorts ports;
32+
33+ users.users.mfi = {
34+ uid = config.ids.uids.mfi;
35+ description = "mFi controller daemon user";
36+ home = "${stateDir}";
37+ };
38+
39+ # We must create the binary directories as bind mounts instead of symlinks
40+ # This is because the controller resolves all symlinks to absolute paths
41+ # to be used as the working directory.
42+ systemd.mounts = map ({ what, where }: {
43+ bindsTo = [ "mfi.service" ];
44+ partOf = [ "mfi.service" ];
45+ unitConfig.RequiresMountsFor = stateDir;
46+ options = "bind";
47+ what = what;
48+ where = where;
49+ }) mountPoints;
50+
51+ systemd.services.mfi = {
52+ description = "mFi controller daemon";
53+ wantedBy = [ "multi-user.target" ];
54+ after = [ "network.target" ] ++ systemdMountPoints;
55+ partOf = systemdMountPoints;
56+ bindsTo = systemdMountPoints;
57+ unitConfig.RequiresMountsFor = stateDir;
58+
59+ preStart = ''
60+ # Clear ./webapps each run.
61+ rm -rf "${stateDir}/webapps"
62+ mkdir -p "${stateDir}/webapps"
63+ ln -s "${pkgs.mfi}/webapps/ROOT.war" "${stateDir}/webapps"
64+
65+ # Copy initial config only once.
66+ test -e "${stateDir}/conf" || cp -ar "${pkgs.mfi}/conf" "${stateDir}/conf"
67+ test -e "${stateDir}/data" || cp -ar "${pkgs.mfi}/data" "${stateDir}/data"
68+
69+ # Fix Permissions.
70+ # (Bind-mounts cause errors; ignore exit codes)
71+ chown -fR mfi: "${stateDir}" || true
72+ chmod -fR u=rwX,go= "${stateDir}" || true
73+ '';
74+
75+ postStop = ''
76+ rm -rf "${stateDir}/webapps"
77+ '';
78+
79+ serviceConfig = {
80+ Type = "simple";
81+ ExecStart = "${cmd} start";
82+ ExecStop = "${cmd} stop";
83+ User = "mfi";
84+ PermissionsStartOnly = true;
85+ UMask = "0077";
86+ WorkingDirectory = "${stateDir}";
87+ };
88+ };
89+ };
90+}