Search code examples
cmakepackagedebiansystemdcpack

How to correctly add a systemd service to a cpack generated debian package?


I am trying to generate a debian package via cpack that respects the system configuration (as in don't start the service if the admin doesn't want it to) and that does not cause errors when being installed in a systemd free environment (as in some docker images).

My current setup consist out of a postinst and a prerm file that are simple given to cpack via CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA. These call systemctl enable/start/stop/disable in both scripts.

From what I have gathered one should call dh_installsystemd --name=foo foo.service for starting services.

Replacing systemctl enable foo.service with that in my postinst file however causes an error:

dh_installsystemd: error: "debian/control" not found. Are you sure you are in the correct directory?
dpkg: error processing package foo (--configure):
 installed foo package post-installation script subprocess returned error exit status 255
Processing triggers for libc-bin (2.31-0ubuntu9.2) ...
Errors were encountered while processing:
 foo

I must confess that I am somewhat lost as to how this should be handled. How does one correctly add a systemd service to a debian package via CPack?


Solution

  • The best solution that has come to mind is to dissect another package and use the same commands dh_installsystemd generates.

    This results in a postinst file like:

    # End automatically added section
    # Based on output by dh_installsystemd/13.5.2
    
    if [ \"$1\" = \"configure\" ] || [ \"$1\" = \"abort-upgrade\" ] || [ \"$1\" = \"abort-deconfigure\" ] || [ \"$1\" = \"abort-remove\" ] ; then
    
        # was-enabled defaults to true, so new installations run enable.
        if deb-systemd-helper --quiet was-enabled 'foo.service'; then
            # Enables the unit on first installation, creates new
            # symlinks on upgrades if the unit file has changed.
            deb-systemd-helper enable 'foo.service' >/dev/null || true
        else
            # Update the statefile to add new symlinks (if any), which need to be
            # cleaned up on purge. Also remove old symlinks.
            deb-systemd-helper update-state 'foo.service' >/dev/null || true
        fi
    fi
    if [ \"$1\" = \"configure\" ] || [ \"$1\" = \"abort-upgrade\" ] || [ \"$1\" = \"abort-deconfigure\" ] || [ \"$1\" = \"abort-remove\" ] ; then
        if [ -z \"${DPKG_ROOT\:-}\" ] && [ -d /run/systemd/system ]; then
            systemctl --system daemon-reload >/dev/null || true
            deb-systemd-invoke restart 'foo.service' >/dev/null || true
        fi
    fi
    
    

    Since these instructions are static updates in the macros have to be manually applied.