etc: remove obsolete directories

This patch adds handling of a directory becoming a symlink in
/etc. Before this patch, the directory wasn't removed and then
symlinking failed, which caused directory not being updated at all.

The idea for the patch goes to @abbradar at
https://github.com/NixOS/nixpkgs/issues/16978#issuecomment-232921903:
> A heuristic idea for this -- a function `isStatic :: Path -> Bool`:
>
> * if path `/etc/foo` is a file, return True iff it's a symlink to `/etc/static/foo`.
> * if path is a directory, return True iff for all items in it `isStatic` is True.
>
> On any conflicts, if old path is static, it's safe to replace and/or
> delete stale. Otherwise make a backup and notify the user via a
> journal entry and console output.

The only difference here -- it will not replace user configs.

This also fixes https://github.com/NixOS/nixpkgs/issues/16978.

+37
+37
nixos/modules/system/etc/setup-etc.pl
··· 22 # current configuration. 23 atomicSymlink $etc, $static or die; 24 25 26 # Remove dangling symlinks that point to /etc/static. These are 27 # configuration files that existed in a previous configuration but not ··· 63 my $target = "/etc/$fn"; 64 File::Path::make_path(dirname $target); 65 $created{$fn} = 1; 66 if (-e "$_.mode") { 67 my $mode = read_file("$_.mode"); chomp $mode; 68 if ($mode eq "direct-symlink") {
··· 22 # current configuration. 23 atomicSymlink $etc, $static or die; 24 25 + # Returns 1 if the argument points to the files in /etc/static. That 26 + # means either argument is a symlink to a file in /etc/static or a 27 + # directory with all children being static. 28 + sub isStatic { 29 + my $path = shift; 30 + 31 + if (-l $path) { 32 + my $target = readlink $path; 33 + return substr($target, 0, length "/etc/static/") eq "/etc/static/"; 34 + } 35 + 36 + if (-d $path) { 37 + opendir DIR, "$path" or return 0; 38 + my @names = readdir DIR or die; 39 + closedir DIR; 40 + 41 + foreach my $name (@names) { 42 + next if $name eq "." || $name eq ".."; 43 + unless (isStatic("$path/$name")) { 44 + return 0; 45 + } 46 + } 47 + return 1; 48 + } 49 + 50 + return 0; 51 + } 52 53 # Remove dangling symlinks that point to /etc/static. These are 54 # configuration files that existed in a previous configuration but not ··· 90 my $target = "/etc/$fn"; 91 File::Path::make_path(dirname $target); 92 $created{$fn} = 1; 93 + 94 + # Rename doesn't work if target is directory. 95 + if (-l $_ && -d $target) { 96 + if (isStatic $target) { 97 + rmtree $target or warn; 98 + } else { 99 + warn "$target directory contains user files. Symlinking may fail."; 100 + } 101 + } 102 + 103 if (-e "$_.mode") { 104 my $mode = read_file("$_.mode"); chomp $mode; 105 if ($mode eq "direct-symlink") {