cleverca22
6/11/2016 - 8:53 PM

default.nix

{ makeUnit, gnupg }:

makeUnit {
  name = "gpg-agent";
  #type = "forking";
  description = "GnuPG Agent";
  execStart = [
    {
      command = gnupg + "/bin/gpg-agent";
      args = [
        "--daemon"
      ];
    }
  ];
}
[clever@amd-nixos:~/x/85e0e3e7ddcb26d623dd0f51bcae5478-3d27398d9a08344fa13d9a97020aac91fdb99b74]$ nix-repl default.nix 
Welcome to Nix version 1.11.2. Type :? for help.

Loading ‘default.nix’...
Added 5 variables.

nix-repl> units
[ «derivation /nix/store/b916ygzfyhiarwlj4xnc1kjdnsn3c6b2-gpg-agent.drv» ]

nix-repl> importUnitFile 
«lambda»

nix-repl> makeUnit 
«lambda»

nix-repl> :b userServices 
warning: you did not specify ‘--add-root’; the result might be removed by the garbage collector
/nix/store/4ywyzhfrr8vafsycg4ri7zpcgdpgzm27-userservices

this derivation produced the following outputs:
  out -> /nix/store/4ywyzhfrr8vafsycg4ri7zpcgdpgzm27-userservices

nix-repl> :q
[clever@amd-nixos:~/x/85e0e3e7ddcb26d623dd0f51bcae5478-3d27398d9a08344fa13d9a97020aac91fdb99b74]$ nix-build default.nix --show-trace
these derivations will be built:
  /nix/store/b916ygzfyhiarwlj4xnc1kjdnsn3c6b2-gpg-agent.drv
  /nix/store/kshasn2jxp28sb7ydv1pgdq9dyl772k7-userservices.drv
building path(s) ‘/nix/store/kxj4l95jz8w9pv4cf8w0pj9l4inviq2h-gpg-agent’
building path(s) ‘/nix/store/4ywyzhfrr8vafsycg4ri7zpcgdpgzm27-userservices’
created 1 symlinks in user environment
/nix/store/4ywyzhfrr8vafsycg4ri7zpcgdpgzm27-userservices

[clever@amd-nixos:~/x/85e0e3e7ddcb26d623dd0f51bcae5478-3d27398d9a08344fa13d9a97020aac91fdb99b74]$ ls -ltrh result/
total 512
lrwxrwxrwx 1 root root 71 Dec 31  1969 gpg-agent.service -> /nix/store/kxj4l95jz8w9pv4cf8w0pj9l4inviq2h-gpg-agent/gpg-agent.service

[clever@amd-nixos:~/x/85e0e3e7ddcb26d623dd0f51bcae5478-3d27398d9a08344fa13d9a97020aac91fdb99b74]$ cat result/gpg-agent.service 
[Unit]
Description = GnuPG Agent
[Service]
ExecStart = /nix/store/j45xz52zawkdq0g711krkhlzfx2d749m-gnupg-2.1.11/bin/gpg-agent --daemon
{ lib, writeTextFile, buildEnv, callPackage }:

with lib;
with builtins;
let
  makeExecStart = { command, args }:
    ''ExecStart = ${command} ${lib.concatStringsSep " " args}'';
  makeUnit = { name, description, execStart }: writeTextFile {
    name = name;
    text = ''
      [Unit]
      Description = ${description}
      [Service]
      ${lib.concatStringsSep "\n" (map makeExecStart execStart)}
    '';
    destination = "/${name}.service";
  };
  importUnitFile = fileName: callPackage (./units + "/${fileName}") { inherit makeUnit; };
  units = map importUnitFile (lib.attrNames (builtins.readDir ./units));
in {
  userServices = buildEnv {
    name = "userservices";
    paths = units;
  };
  inherit importUnitFile units makeUnit makeExecStart;
}