#!/usr/bin/perl -w


use v5.10.1;
use strict;
use Debian::Debhelper::Dh_Lib;
use File::Find;
use File::Path qw(make_path);
use File::stat;
use Text::Hogan::Compiler;
use File::Slurp qw(read_file write_file);
use File::Copy::Recursive qw(dircopy);
use feature 'signatures';
no warnings 'experimental';

our $VERSION = "2.9.0";

# Create empty file {dest} and all required parent directories.
sub create_empty_file {
    my ($dest) = @_;
    make_path(dirname($dest));
    write_file($dest, '') || die $!;
}

# Render mustache template {name} from data directory into {dest},
# substituting {values} hash. If {perm} argument is provided, it is used
# set permissions of {dest}. Intermediate directories to ${dest} are
# created as needed.
#
# Data directory is specified by {DH_RUNIT_DATADIR} environment
# variable, and defaults to /usr/share/dh-runit/data.
sub template_from_data_directory {
    my ($name, $dest, $values, $perm) = @_;
    my $datadir = $ENV{DH_RUNIT_DATADIR} || "/usr/share/dh-runit/data";
    my $template = read_file("${datadir}/${name}");
    my $compiler = Text::Hogan::Compiler->new;
    my $output = $compiler->compile($template)->render($values);

    create_empty_file($dest);
    write_file($dest, $output);

    if (defined $perm) {
        chmod $perm, $dest;
    }
}

sub parse_options($opts) {
    my $conf = { enable => 1 };
    for my $opt (split(/,/, $opts)) {
        given($opt) {
            when (/^disable$/)     { $conf->{enable} = 0; };
            when (/^name=(.*)$/)   { $conf->{name} = $1; };
            when (/^since=(.*)$/)  { $conf->{since} = $1; };
            when (/^logscript$/)   { $conf->{logscript} = 1};
            when (/^noreplace$/)   { $conf->{noreplace} = 1};
            when (/^presubj$/)     { $conf->{presubj} = 1; };
            when (/^defaults$/)    { "do nothing"; };
            default                { error("unknown option `$opt'"); }
        }
    }
    return $conf;
}

sub ensure_executable($directory) {
    my @scripts = (
        'run',
        'finish',
        'check',
        'log/run',
        'log/finish',
        'control/c',
        'control/d',
        'control/t',
        'control/u',
        'control/x',
    );

    for my $f (@scripts) {
        my $file = "$directory/$f";
        doit('chmod', '+x', $file) if (-e $file);
    }
}

sub runit_autoscript($pkg, $script, $sed) {
    autoscript($pkg, $script, "$script-runit", $sed);
}

init();

PKG: foreach my $pkg (@{$dh{DOPACKAGES}}) {
    next if is_udeb($pkg);

    my @entries = ();
    if (my $pkgfile = pkgfile($pkg, 'runit')) {
        @entries = filedoublearray($pkgfile);
    }
    while (@ARGV) {
        (my $path, my $opts) = splice(@ARGV, 0, 2);
        push @entries, [$path, $opts];
    }

    next unless @entries;

    my $tmp = tmpdir($pkg);
    my $sv_dir = "$tmp/etc/sv";

    for (@entries) {
        (my $path, my $opts) = @$_;
        error("can't read `$path'") unless -r $path;

        my $conf = parse_options($opts);
        my $name = $conf->{name} || basename($path);

        if ($conf->{noreplace}) {
            create_empty_file("${tmp}/usr/share/runit/meta/${name}/noreplace");
        }

        # These files allow handling of uninstalled-not-purged situation.
        create_empty_file("${tmp}/usr/share/runit/meta/${name}/installed");
        create_empty_file("${tmp}/etc/sv/${name}/.meta/installed");

        if ( -f $path) {
            install_dir("$sv_dir/$name");
            install_prog($path, "$sv_dir/$name/run");
        } elsif ( -d $path) {
            dircopy($path, "$sv_dir/$name");
            # Unfortunately, dh_fixperms does not handle executable bit here.
            ensure_executable("$sv_dir/$name");
        }
        make_symlink("/etc/sv/$name/supervise", "/run/runit/supervise/$name", $tmp);
        install_dir("$tmp/etc/runit/runsvdir/default");

        my $substitutions = {
            NAME   => $name,
            ENABLE => $conf->{enable} ? "yes" : "no"
        };

        runit_autoscript($pkg, 'postrm', $substitutions);
        runit_autoscript($pkg, 'postinst', $substitutions);

        if ($conf->{since}) {
            warning("the since option is deprecated and will be removed in future release of dh-runit");
        }
        
        if ($conf->{logscript}) {
            my $logdir = "/var/log/runit/$name";

            install_dir("$sv_dir/$name/log");
            install_dir($tmp . $logdir);

            template_from_data_directory('logscript', "$sv_dir/$name/log/run",
                                         { logdir => $logdir }, 0755);

            make_symlink("/etc/sv/$name/log/supervise", "/run/runit/supervise/$name.log", $tmp);
        }

        if ($conf->{presubj}) {
            if ( -e "debian/$pkg.bug-presubj") {
		warning("presubj for $pkg already exists and takes precedence, runit presubj file not installed")
            }
	    else {
             template_from_data_directory('presubj', "$tmp/usr/share/bug/$pkg/presubj",
                                          { pkg => $pkg }, 0644);
	    }
         }
    }
    # runit=2.1.2-20 introduced 'runit-log' user
    # runit=2.1.2-23 introduced /lib/runit/invoke-run
    # runit=2.1.2-36 introduced '_runit-log' user
    # runit-helper 2.8.15 use dotlinks to mark a service as disabled, 'since' option is deprecated
    # runit-helper 2.9.0 has code for loguser transition
    addsubstvar($pkg, 'runit:Conflicts', 'runit', '<< 2.1.2-36~');
    addsubstvar($pkg, 'runit:Breaks', 'runit', '<< 2.1.2-36~');
    addsubstvar($pkg, 'misc:Depends', 'runit-helper', '>= 2.9.0~');
}

# PROMISE: DH NOOP WITHOUT runit

=head1 NAME

dh_runit - install/enable runit runscripts

=head1 SYNOPSIS

B<dh_runit> [S<I<debhelper options>>] [I<path> I<options>] ...

=head1 DESCRIPTION

B<dh_runit> is a debhelper program that is responsible for
installing and enabling I<runit> runscripts. If a file named
F<debian/I<package>.runit> exists, then it ensures appropriate actions
are performed based on its content.

For runit, each unit of supervision (or, simply speaking, program) is
represented by a directory under F</etc/sv>, containing at least a F<run>
executable file. Each enabled unit of supervision is represented by a
symbolic link under F</etc/services> (which itself is a symbolic link to
F</etc/runit/runsvdir/default>) pointing to some directory under
F</etc/sv>.

B<dh_runit> reads arguments from the command line and
F<debian/I<package>.runit> in pairs, with the first item being the
path to a file or directory and the second being a set of options.
If the first argument names a file, it is treated as a 'run' script
to be installed at F</etc/sv/*/run> as an executable file. If the first
argument names a directory, that directory is copied as a whole to
F</etc/sv>.

Options are comma separated, like mount options. Unrecognized options
are errors. The following options are recognized:

=over

=item I<disable>

Install the runscript but do not enable it by default.
This means that the corresponding service will not be started.
The service can be enabled manually by the system administrator or
automatically using update-service(8).

=item I<name>=preferred-name

By default, the name of the directory under F</etc/sv> for a given
runscript is the basename of the path argument naming it. This
option allows overriding that default with an explicitly chosen
directory name.

=item I<logscript>

Install a standard F<log/run> script that invokes svlogd(8) with
the rights of the dedicated user. Specifying this option produces
an error if the path argument names a directory that already
contains a F</log/run> script.

=item I<since>

Since dh-runit 2.8.15 this option is no longer needed and is deprecated.
It's retained only for backward compatibility with packages that still
use it. See #942323

=item I<noreplace>

Mark service as non-restartible. Interpreter B<invoke-run>, provided by
I<runit> package does not stop sysvinit-managed instance of service to
replace it with runit-managed instance when service is marked as
non-restartible.

Display managers (xdm, kdm, ...) are examples of non-restartible services.

=item I<presubj>

Include presubj file for reportbug into generate package. This file contains
note that suggest including runit maintainers into copy of bug reports, related
to runit integration. If the package already include it's own presubj file, that file
takes precedence over runit presubj file.

This may make life of package maintainer who uses another init system easier.

=item I<defaults>

If you don't need other options, specify this one.

=back

=head1 SUBSTITUTION VARIABLES

Packages using B<dh_runit> do not depend on B<runit> but should include the
I<runit:Breaks> variable in their I<Breaks> field in I<debian/control>
to ensure that no breakages are caused by a too-old version of B<runit> package.

=head1 EXAMPLES

This section contains several example F<I<package>.runit> snippets.

  # In this case, a file is installed as a 'run' script. The directory
  # name under /etc/sv is derived from the file's basename (/etc/sv/script).
  path/to/file/to/be/installed/as/run/script defaults

  # Similar, but installs a directory as a whole. It is the package's
  # responsibility to ensure this directory contains everything required.
  path/to/directory defaults

  # Similar, but without creating a symlink under /etc/service.
  path/to/directory disable

  # Explicitly specifying a name to use for the directory under /etc/sv.
  # A standard log/run script will be created.
  path/to/directory name=my-preferred-name,logscript

=cut

# vim: et:sw=4
