Fix installing an installed running process (#941)

diff --git a/pkg/private/install.py.tpl b/pkg/private/install.py.tpl
index 93c3967..ddd6dfe 100644
--- a/pkg/private/install.py.tpl
+++ b/pkg/private/install.py.tpl
@@ -23,6 +23,7 @@
 import pathlib
 import shutil
 import sys
+import tempfile
 
 from pkg.private import manifest
 
@@ -79,7 +80,19 @@
 
     def _do_file_copy(self, src, dest):
         logging.debug("COPY %s <- %s", dest, src)
-        shutil.copyfile(src, dest)
+        # Copy to a temporary file and then move it to the destination.
+        # This ensures code-signed executables on certain platforms
+        # behave correctly.
+        # See: https://developer.apple.com/documentation/security/updating-mac-software
+        # Use `dir` to ensure the temporary file is created on the same file system as the destination,
+        # to avoid cross-filesystem replace which is an error on some platforms.
+        with tempfile.NamedTemporaryFile(delete=False, dir=os.path.dirname(dest)) as tmp_file:
+            try:
+                shutil.copyfile(src, tmp_file.name)
+                os.replace(tmp_file.name, dest)
+            except:
+                pathlib.Path(tmp_file.name).unlink(missing_ok=True)
+                raise
 
     def _do_mkdir(self, dirname, mode):
         logging.debug("MKDIR %s %s", mode, dirname)