Debian Codegraph @

convert-etc-shells

raw
1 #!/usr/bin/perl
2 # vim: shiftwidth=4 tabstop=4
3 #
4 # Copyright 2016-2022 by Marco d'Itri <[email protected]>
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 use warnings;
12 use strict;
13 use autodie;
14 use v5.16;
15
16 convert($ARGV[0] || '/etc/shells');
17 exit;
18
19 sub convert {
20 my ($file) = @_;
21
22 my (@shells, @nonusr_shells, %seen_in_usr);
23
24 open(my $in, '<', $file);
25 while (<$in>) {
26 chomp;
27 push(@shells, $_);
28 $seen_in_usr{$1} = 1 if m#^/usr(/s?bin/.+)#;
29 push(@nonusr_shells, $_) if m#^/s?bin/#;
30 }
31 close $in;
32
33 my @new_shells = # and add them to the list
34 map { "/usr$_" } # add /usr to their path
35 grep { not $seen_in_usr{$_} } # if they do not already exist in /usr
36 @nonusr_shells; # for each shell not in /usr
37
38 return unless @new_shells;
39
40 umask(0022);
41 open(my $out, '>', "$file.tmp");
42 say $out $_ foreach @shells, @new_shells;
43 close $out;
44
45 rename("$file.tmp", $file);
46 restore_context($file);
47 }
48
49 sub safe_system {
50 my (@cmd) = @_;
51
52 my $rc = system(@cmd);
53 die "Failed to execute @cmd: $!\n" if $rc == -1;
54 die "@cmd: rc=" . ($? >> 8) . "\n" if $rc;
55 }
56
57 sub restore_context {
58 my ($file) = @_;
59
60 return if not -x '/sbin/restorecon';
61
62 safe_system('restorecon', $file);
63 }
64