#!/usr/bin/perl
# dh_sysuser --- debhelper to create system users

# Copyright (C) 2016 Dmitry Bogatov <kaction@sagulo>

# Author: Dmitry Bogatov <kaction@sagulo>

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

use 5.014;
use strict;
use Debian::Debhelper::Dh_Lib;
use File::Find;
use File::stat;
use feature 'signatures';
use feature 'switch';
no warnings 'experimental::signatures';
no warnings 'experimental::smartmatch';

init();

sub parse_options($conf, $options, $user) {
    foreach my $opt (split(/,/, $options)) {
        given ($opt) {
            when (/^home=(.*)$/)  { $conf->{home} = $1; }
            when (/^home$/)       {
                my $normal = $user;
                $normal =~ s/^_+//;         # strip leading
                $normal =~ s/_+$//;         # and trailing underscore
                $normal =~ s/^[Dd]ebian-//; # and discouraged debian- prefix
                $conf->{home} = "/var/lib/$normal";
            }
            when (/^defaults$/)   { "do nothing"; }
            default               { error("unknown option `$opt'"); }
        }
    }
}

foreach my $pkg (@{$dh{DOPACKAGES}}) {
    my @entries = ();
    if (@ARGV) {
        while (@ARGV) {
            (my $user, my $opt) = splice(@ARGV, 0, 2);
            push @entries, [$user, $opt];
        }
    } elsif (my $cfg = pkgfile($pkg, 'sysuser')) {
        @entries = filedoublearray($cfg);
    };
    foreach my $entry (@entries) {
        (my $user, my $opts) = @$entry;
        $opts ||= 'defaults';
        my %conf = (home => '/nonexistent');
        parse_options(\%conf, $opts, $user);
        foreach my $script (qw/prerm postinst/) {
            autoscript($pkg, $script, "$script-sysuser",
                       sub { s/%HOME%/$conf{home}/;
                             s/%PACKAGE%/$pkg/;
                             s/%USERNAME%/$user/;});
        }
    }
    # every time maintainer script changes, minor version must be bumped.
    addsubstvar($pkg, 'misc:Depends', 'sysuser-helper', '<< 1.4');
}

# PROMISE: DH NOOP WITHOUT sysuser
=head1 NAME

dh_sysuser - manage system users, required for package operation

=head1 SYNOPSIS

B<dh_sysuser> [S<I<debhelper options>>] [I<username> I<options>] ...

=head1 DESCRIPTION

B<dh_sysuser> is debhelper addon, that provide simple and uniform way
of creating and removing system users, required for package operation
(for example, to run with dropped privileges).

Process of user creation is delegated to useradd(8) utility, whose
behavior is controlled by F</etc/login.defs> configuration file. In
default installation, 

=over

=item -

New user have primary group of same name. It is not be member of any
other groups.

=item -

New user have '!' in F</etc/shadow> password field, making it impossible
to login.

=item -

New user have F</usr/sbin/nologin> as its shell. You still can get new
user's shell with I<su -s>.

=item -

If home directory is created (see below), its permissions are affected
by B<UMASK> variable in F</etc/login.defs>. By default, it results 0755.
Files from F</etc/skel> are I<NOT> copied.

B<WARNING:> Paragraph above means that data, stored in new user's home
directory is world-readable. If you, as package maintainer, need full
control over home directory permissions, you are welcome to file a bug.

=back

B<dh_sysuser> read its arguments from command line and file
F<debian/I<package>.F<sysuser>> in pairs, first one being an username
and second one is options. The configuration file or commandline
arguments must be used to create users: just calling `dh_sysuser`
without arguments does nothing. Here are the options that can be
specified after the username:

=over


=item I<home>

This option request creation of home directory in
F</var/lib/B<username>>. Probably, you should use this form over
explicit one, described below, for uniformity.

=item I<home>=F</path/to/home/directory>

This option requests creation of home directory at specified path

=item I<defaults>

If you do not need any other options, put this one.

=back

=head2 CRUFT OF SYSTEM USERS

While it is easy to create system user (and user in general), it is hard
to say, when it is safe to remove it. What should happen to its home
directory? What about files outside of home directory? There was some of
discussion (#848239, #848240), and no simple and definitive solution
arised. So far, dh-sysuser do the following on package removal:

=over

=item -

If user have been created without home directory, it is considered safe
to remove it.

=item -

If user have been created with home directory, but at time of package
removal it is still empty, it is considered safe to remove both user and
his empty home directory.

=item -

If user have been created with home directory, but at time of package
removal it is B<not> empty, both user and its home directory are left
alone.

B<NOTE:> As package maintainer, you are encouraged to delete from home
directory files, known to be of little value. It increases chances that
home directory will become empty, and user will be removed.

=back

=head1 EXAMPLES

In F<debian/I<package>.F<sysuser>>, this will create a B<foo> user with
defaults settings, will create a home in the default location for B<bar>,
and a custom location for B<baz>:

    foo defaults
    bar home
    baz home=/opt/baz

=head1 SEE ALSO

useradd(8)

=cut
