From: Martin Pitt <martin.pitt@ubuntu.com>
Date: Wed, 21 Jan 2015 10:25:14 +0100
Subject: sysv-generator: Replace Provides: symlinks with real units

Since commit b7e7184 the SysV generator creates symlinks for all "Provides:" in
the LSB header. However, this is too greedy; there are cases where the
creation of a unit .service file fails because of an already existing
symlink with the same name:

 - Backup files such as /etc/init.d/foo.bak still have "Provides: foo", and
   thus get a foo.service -> foo.bak.service link. foo.bak would not be enabled
   in rcN.d/, but we (deliberately) create units for all executables in init.d/
   so that a manual "systemctl start" works. If foo.bak is processed before,
   the symlink already exists.

 - init.d/bar has "Provides: foo", while there also is a real init.d/foo. The
   former would create a link foo.service -> bar.service, while the latter
   would fail to create the real foo.service.

Keeping track of which alias symlinks we actually want is error prone, and
restricting the creation of services for enabled init.d scripts would reduce
the utility of the generator (for manual starting disabled init.d scripts) as
well as not cover the second case. So if we encounter an existing symlink, just
remove it before writing a real unit.

Note that two init.d scripts "foo" and "bar" which both provide the same name
"common" already work. The first processed init script wins and creates the
"common.service" symlink, and the second just fails to create the symlink
again.

Bug-Debian: https://bugs.debian.org/775404
---
 src/sysv-generator/sysv-generator.c | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/src/sysv-generator/sysv-generator.c b/src/sysv-generator/sysv-generator.c
index b7b62d6..628d579 100644
--- a/src/sysv-generator/sysv-generator.c
+++ b/src/sysv-generator/sysv-generator.c
@@ -153,6 +153,7 @@ static int generate_unit_file(SysvStub *s) {
         _cleanup_free_ char *wants = NULL;
         _cleanup_free_ char *conflicts = NULL;
         int r;
+        struct stat st;
 
         before = strv_join(s->before, " ");
         if (!before)
@@ -174,6 +175,14 @@ static int generate_unit_file(SysvStub *s) {
         if (!unit)
                 return log_oom();
 
+        /* We might already have a symlink with the same name from a Provides:,
+         * or from backup files like /etc/init.d/foo.bak. Real scripts always win,
+         * so remove an existing link */
+        if (lstat(unit, &st) == 0 && S_ISLNK(st.st_mode)) {
+                log_warning("Overwriting existing symlink %s with real service", unit);
+                unlink(unit);
+        }
+
         f = fopen(unit, "wxe");
         if (!f) {
                 log_error("Failed to create unit file %s: %m", unit);
