]> Sergey Matveev's repositories - public-inbox.git/blob - script/public-inbox-watch
watch: add --help/-h support
[public-inbox.git] / script / public-inbox-watch
1 #!/usr/bin/perl -w
2 # Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 my $help = <<EOF;
5 usage: public-inbox-watch
6
7 See public-inbox-watch(1) man page for full documentation.
8 EOF
9
10 use strict;
11 use Getopt::Long qw(:config gnu_getopt no_ignore_case auto_abbrev);
12 use IO::Handle; # ->autoflush
13 use PublicInbox::Watch;
14 use PublicInbox::Config;
15 use PublicInbox::DS;
16 use PublicInbox::Sigfd;
17 use PublicInbox::Syscall qw($SFD_NONBLOCK);
18 my $do_scan = 1;
19 GetOptions('scan!' => \$do_scan, # undocumented, testing only
20         'help|h' => \(my $show_help)) or do { print STDERR $help; exit 1 };
21 if ($show_help) { print $help; exit 0 };
22 my $oldset = PublicInbox::Sigfd::block_signals();
23 STDOUT->autoflush(1);
24 STDERR->autoflush(1);
25 local $0 = $0; # local since this script may be eval-ed
26 my $watch = PublicInbox::Watch->new(PublicInbox::Config->new);
27 my $reload = sub {
28         my $prev = $watch or return; # SIGQUIT issued
29         $watch->quit;
30         $watch = PublicInbox::Watch->new(PublicInbox::Config->new);
31         if ($watch) {
32                 warn("I: reloaded\n");
33         } else {
34                 warn("E: reloading failed\n");
35                 $watch = $prev;
36         }
37 };
38
39 if ($watch) {
40         my $scan = sub {
41                 return if !$watch;
42                 warn "I: scanning\n";
43                 $watch->trigger_scan('full');
44         };
45         my $quit = sub {
46                 $watch->quit if $watch;
47                 $watch = undef;
48                 $0 .= ' quitting';
49         };
50         my $sig = {
51                 HUP => $reload,
52                 USR1 => $scan,
53                 CHLD => \&PublicInbox::DS::enqueue_reap,
54         };
55         $sig->{QUIT} = $sig->{TERM} = $sig->{INT} = $quit;
56
57         # --no-scan is only intended for testing atm, undocumented.
58         PublicInbox::DS::requeue($scan) if $do_scan;
59
60         my $sigfd = PublicInbox::Sigfd->new($sig, $SFD_NONBLOCK);
61         local %SIG = (%SIG, %$sig) if !$sigfd;
62         if (!$sigfd) {
63                 PublicInbox::Sigfd::set_sigmask($oldset);
64                 PublicInbox::DS->SetLoopTimeout(1000);
65         }
66         $watch->watch($sig, $oldset) while ($watch);
67 }