#!perl

our $DATE = '2019-05-22'; # DATE
our $VERSION = '0.001'; # VERSION

use 5.010001;
use strict;
use warnings;

use Perinci::CmdLine::Any;
use Perinci::Sub::Util qw(gen_modified_sub);
use Proc::Govern;

my $res = gen_modified_sub(
    output_name => 'govproc',
    base_name   => 'Proc::Govern::govern_process',
    modify_meta => sub {
        $_[0]{result_naked} = 0;
    },
    output_code => sub {
        my %args = @_;
        my $exit_code = Proc::Govern::govern_process(%args);
        [200, "OK", '', {'cmdline.exit_code' => $exit_code}];
    },
);
$res->[0] == 200 or die "Can't generate modified sub: $res->[0] - $res->[1]";

Perinci::CmdLine::Any->new(
    url => '/main/govproc',
    log => 1,
)->run;

# ABSTRACT: Perinci::CmdLine-based variant of govproc CLI
# PODNAME: govproc-pericmd

__END__

=pod

=encoding UTF-8

=head1 NAME

govproc-pericmd - Perinci::CmdLine-based variant of govproc CLI

=head1 VERSION

This document describes version 0.001 of govproc-pericmd (from Perl distribution App-govproc-pericmd), released on 2019-05-22.

=head1 SYNOPSIS

Use as you would use L<govproc>:

 % govproc-pericmd --euid tono --timeout '2.5 hours' ...

=head1 DESCRIPTION

This script is just like L<govproc> but uses the L<Perinci::CmdLine> CLI
framework to give you conveniences like shell tab completion and argument
coercions (see the above example in Synopsis).

=head1 OPTIONS

C<*> marks required options.

=head2 Main options

=over

=item B<--command-json>=I<s>

Command to run (JSON-encoded).

See C<--command>.

=item B<--command>=I<s@>*

Command to run.

Passed to <pm:IPC::Run>'s `start()`.


Can be specified multiple times.

=item B<--killfam>

Instead of kill, use killfam (kill family of process).

This can be useful e.g. to control load more successfully, if the
load-generating processes are the subchildren of the one we're governing.

This requires <pm:Proc::Killfam> CPAN module, which is installed separately.


=item B<--name>=I<s>

Should match regex `\A\w+\z`. Used in several places, e.g. passed as `prefix` in
<pm:File::Write::Rotate>'s constructor as well as used as name of PID file.

If not given, will be taken from command.


=item B<--pid-dir>=I<s>

Directory to put PID file in.

=back

=head2 Configuration options

=over

=item B<--config-path>=I<filename>, B<-c>

Set path to configuration file.

=item B<--config-profile>=I<s>, B<-P>

Set configuration profile to use.

=item B<--no-config>, B<-C>

Do not use any configuration file.

=back

=head2 Environment options

=over

=item B<--no-env>

Do not read environment for default options.

=back

=head2 Instance control options

=over

=item B<--on-multiple-instance>=I<s>

Valid values:

 ["exit"]

Can be set to `exit` to silently exit when there is already a running instance.
Otherwise, will print an error message `Program <NAME> already running`.


=item B<--single-instance>

If set to true, will prevent running multiple instances simultaneously.
Implemented using <pm:Proc::PID::File>. You will also normally have to set
`pid_dir`, unless your script runs as root, in which case you can use the
default `/var/run`.


=back

=head2 Load control options

=over

=item B<--load-check-every>=I<s>

Frequency of load checking.

Default value:

 10

=item B<--load-high-limit-json>=I<s>

See C<--load-high-limit>.

=item B<--load-high-limit>=I<s>

Limit above which program should be suspended, if load watching is enabled. If
integer, will be compared against <pm:Unix::Uptime>`->load`'s `$load1` value.
Alternatively, you can provide a custom routine here, code should return true if
load is considered too high.

Note: `load_watch` needs to be set to true first for this to be effective.


=item B<--load-low-limit-json>=I<s>

See C<--load-low-limit>.

=item B<--load-low-limit>=I<s>

Limit below which program should resume, if load watching is enabled. If
integer, will be compared against <pm:Unix::Uptime>`->load`'s `$load1` value.
Alternatively, you can provide a custom routine here, code should return true if
load is considered low.

Note: `load_watch` needs to be set to true first for this to be effective.


=item B<--load-watch>

If set to 1, enable load watching. Program will be suspended when system load is
too high and resumed if system load returns to a lower limit.


=back

=head2 Logging options

=over

=item B<--debug>

Shortcut for --log-level=debug.

=item B<--log-level>=I<s>

Set log level.

=item B<--log-stderr-json>=I<s>

Will be passed as arguments to `File::Write::Rotate` (JSON-encoded).

See C<--log-stderr>.

=item B<--log-stderr>=I<s>

Will be passed as arguments to `File::Write::Rotate`.

Specify logging for STDERR. Logging will be done using <pm:File::Write::Rotate>.
Known hash keys: `dir` (STR, defaults to `/var/log`, directory, preferably
absolute, where the log file(s) will reside, should already exist and be
writable, will be passed to <pm:File::Write::Rotate>'s constructor), `size`
(int, also passed to <pm:File::Write::Rotate>'s constructor), `histories` (int,
also passed to <pm:File::Write::Rotate>'s constructor), `period` (str, also
passed to <pm:File::Write::Rotate>'s constructor).


=item B<--log-stdout-json>=I<s>

Will be passed as arguments to `File::Write::Rotate` (JSON-encoded).

See C<--log-stdout>.

=item B<--log-stdout>=I<s>

Will be passed as arguments to `File::Write::Rotate`.

=item B<--quiet>

Shortcut for --log-level=error.

=item B<--trace>

Shortcut for --log-level=trace.

=item B<--verbose>

Shortcut for --log-level=info.

=back

=head2 Output control options

=over

=item B<--no-show-stderr>

Can be used to turn off STDERR output. If you turn this off and set
`log_stderr`, STDERR output will still be logged but not displayed to screen.


=item B<--no-show-stdout>

=back

=head2 Output options

=over

=item B<--format>=I<s>

Choose output format, e.g. json, text.

Default value:

 undef

=item B<--json>

Set output format to json.

=item B<--naked-res>

When outputing as JSON, strip result envelope.

Default value:

 0

By default, when outputing as JSON, the full enveloped result is returned, e.g.:

    [200,"OK",[1,2,3],{"func.extra"=>4}]

The reason is so you can get the status (1st element), status message (2nd
element) as well as result metadata/extra result (4th element) instead of just
the result (3rd element). However, sometimes you want just the result, e.g. when
you want to pipe the result for more post-processing. In this case you can use
`--naked-res` so you just get:

    [1,2,3]


=back

=head2 Restart options

=over

=item B<--restart>

If set to true, do restart.

=back

=head2 Screensaver options

=over

=item B<--no-screensaver>

Prevent screensaver from being activated.

=back

=head2 Setuid options

=over

=item B<--egid>=I<s>

Set EGID(s) of command process.

Need to be root to be able to setuid.


=item B<--euid>=I<s>

Set EUID of command process.

Need to be root to be able to setuid.


=back

=head2 Timeout options

=over

=item B<--timeout>=I<s>

Apply execution time limit, in seconds.

After this time is reached, process (and all its descendants) are first sent the
TERM signal. If after 30 seconds pass some processes still survive, they are
sent the KILL signal.

The killing is implemented using <pm:IPC::Run>'s `kill_kill()`.

Upon timeout, exit code is set to 124.


=back

=head2 Other options

=over

=item B<--help>, B<-h>, B<-?>

Display help message and exit.

=item B<--version>, B<-v>

Display program's version and exit.

=back

=head1 COMPLETION

This script has shell tab completion capability with support for several
shells.

=head2 bash

To activate bash completion for this script, put:

 complete -C govproc-pericmd govproc-pericmd

in your bash startup (e.g. F<~/.bashrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is recommended, however, that you install modules using L<cpanm-shcompgen>
which can activate shell completion for scripts immediately.

=head2 tcsh

To activate tcsh completion for this script, put:

 complete govproc-pericmd 'p/*/`govproc-pericmd`/'

in your tcsh startup (e.g. F<~/.tcshrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is also recommended to install L<shcompgen> (see above).

=head2 other shells

For fish and zsh, install L<shcompgen> as described above.

=head1 CONFIGURATION FILE

This script can read configuration files. Configuration files are in the format of L<IOD>, which is basically INI with some extra features.

By default, these names are searched for configuration filenames (can be changed using C<--config-path>): F<~/.config/govproc-pericmd.conf>, F<~/govproc-pericmd.conf>, or F</etc/govproc-pericmd.conf>.

All found files will be read and merged.

To disable searching for configuration files, pass C<--no-config>.

You can put multiple profiles in a single file by using section names like C<[profile=SOMENAME]> or C<[SOMESECTION profile=SOMENAME]>. Those sections will only be read if you specify the matching C<--config-profile SOMENAME>.

You can also put configuration for multiple programs inside a single file, and use filter C<program=NAME> in section names, e.g. C<[program=NAME ...]> or C<[SOMESECTION program=NAME]>. The section will then only be used when the reading program matches.

Finally, you can filter a section by environment variable using the filter C<env=CONDITION> in section names. For example if you only want a section to be read if a certain environment variable is true: C<[env=SOMEVAR ...]> or C<[SOMESECTION env=SOMEVAR ...]>. If you only want a section to be read when the value of an environment variable has value equals something: C<[env=HOSTNAME=blink ...]> or C<[SOMESECTION env=HOSTNAME=blink ...]>. If you only want a section to be read when the value of an environment variable does not equal something: C<[env=HOSTNAME!=blink ...]> or C<[SOMESECTION env=HOSTNAME!=blink ...]>. If you only want a section to be read when an environment variable contains something: C<[env=HOSTNAME*=server ...]> or C<[SOMESECTION env=HOSTNAME*=server ...]>. Note that currently due to simplistic parsing, there must not be any whitespace in the value being compared because it marks the beginning of a new section filter or section name.

List of available configuration parameters:

 command (see --command)
 egid (see --egid)
 euid (see --euid)
 format (see --format)
 killfam (see --killfam)
 load_check_every (see --load-check-every)
 load_high_limit (see --load-high-limit)
 load_low_limit (see --load-low-limit)
 load_watch (see --load-watch)
 log_level (see --log-level)
 log_stderr (see --log-stderr)
 log_stdout (see --log-stdout)
 naked_res (see --naked-res)
 name (see --name)
 no_screensaver (see --no-screensaver)
 on_multiple_instance (see --on-multiple-instance)
 pid_dir (see --pid-dir)
 restart (see --restart)
 show_stderr (see --no-show-stderr)
 show_stdout (see --no-show-stdout)
 single_instance (see --single-instance)
 timeout (see --timeout)

=head1 ENVIRONMENT

=head2 GOVPROC_PERICMD_OPT => str

Specify additional command-line options.

=head1 FILES

F<~/.config/govproc-pericmd.conf>

F<~/govproc-pericmd.conf>

F</etc/govproc-pericmd.conf>

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/App-govproc-pericmd>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-App-govproc-pericmd>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=App-govproc-pericmd>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 SEE ALSO

L<govproc>

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2019 by perlancar@cpan.org.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
