From bc2f2ad54612ade98c89b72dd06c7de39e1a2cde Mon Sep 17 00:00:00 2001
From: Robert Helgesson <robert@rycee.net>
Date: Thu, 16 Nov 2017 15:34:51 +0100
Subject: [PATCH] systemd: honor RefuseManualStart and RefuseManualStop

Fixes https://github.com/rycee/home-manager/issues/140
---
 modules/systemd.nix | 40 ++++++++++++++++++++++++++++++++++------
 1 file changed, 34 insertions(+), 6 deletions(-)

diff --git a/modules/systemd.nix b/modules/systemd.nix
index 8ee2db659..778912a17 100644
--- a/modules/systemd.nix
+++ b/modules/systemd.nix
@@ -119,6 +119,18 @@ in
         );
 
       home.activation.reloadSystemD = dagEntryAfter ["linkGeneration"] ''
+        function isStartable() {
+          local service="$1"
+          [[ $(systemctl --user show -p RefuseManualStart "$service") == *=no ]]
+        }
+
+        function isStoppable() {
+          if [[ -v oldGenPath ]] ; then
+            local service="$1"
+            [[ $(systemctl --user show -p RefuseManualStop "$service") == *=no ]]
+          fi
+        }
+
         function systemdPostReload() {
           local workDir
           workDir="$(mktemp -d)"
@@ -163,19 +175,35 @@ in
             > $servicesDiffFile || true
 
           local -a maybeRestart=( $(grep '^ ' $servicesDiffFile | cut -c2-) )
-          local -a toStop=( $(grep '^-' $servicesDiffFile | cut -c2-) )
-          local -a toStart=( $(grep '^+' $servicesDiffFile | cut -c2-) )
+          local -a maybeStop=( $(grep '^-' $servicesDiffFile | cut -c2-) )
+          local -a maybeStart=( $(grep '^+' $servicesDiffFile | cut -c2-) )
           local -a toRestart=( )
+          local -a toStop=( )
+          local -a toStart=( )
 
           for f in ''${maybeRestart[@]} ; do
-            if ${cfg.systemctlPath} --quiet --user is-active "$f" \
-               && ! cmp --quiet \
-                   "$oldUserServicePath/$f" \
-                   "$newUserServicePath/$f" ; then
+            if isStoppable "$f" \
+                && isStartable "$f" \
+                && ${cfg.systemctlPath} --quiet --user is-active "$f" \
+                && ! cmp --quiet \
+                    "$oldUserServicePath/$f" \
+                    "$newUserServicePath/$f" ; then
               toRestart+=("$f")
             fi
           done
 
+          for f in ''${maybeStop[@]} ; do
+            if isStoppable "$f" ; then
+              toStop+=("$f")
+            fi
+          done
+
+          for f in ''${maybeStart[@]} ; do
+            if isStartable "$f" ; then
+              toStart+=("$f")
+            fi
+          done
+
           rm -r $workDir
 
           local sugg=""