#!/usr/bin/perl -T


use strict;
use warnings;

package Munin::Master::Http;

use HTTP::Server::Simple::CGI::PreFork;
use base qw(HTTP::Server::Simple::CGI::PreFork);

use Munin::Master::Graph;
use Munin::Master::HTML;


sub handle_request {
    my $self = shift;
    my $cgi  = shift;    # XXX - this is NOT thread-safe?

    my $path = $cgi->path_info();

    # Dispatch by extension, so we can have the same URL prefix
    my $is_graph
      = ( $path !~ m/\.html$/x ) && ( $path =~ m/.*-(day|hour|week|month|year|pinpoint).*$/x );
    if ($is_graph) {
        Munin::Master::Graph::handle_request($cgi);
    }
    else {
        Munin::Master::HTML::handle_request($cgi);
    }
    return;
}

package main;    ## no critic qw(Modules::ProhibitMultiplePackages)

use Getopt::Long;

my $listen = ":";

print_usage_and_exit()
  unless GetOptions(
    "listen=s"  => \$listen,
    "version" => \&print_version_and_exit,
    "help"    => \&print_usage_and_exit,
  );

die "ERROR: Invalid listen argument supplied: '$listen'\n" unless $listen =~ /^((\S*|\[\S+\]):)?(\d+)?$/x;
my $host = defined $2 ? $2 : "*";
my $port = defined $3 ? $3 : 4948;

# start the server
Munin::Master::Http->new( { host => $host, port => $port } )->run( prefork => 1, max_servers => 10 );


sub print_usage_and_exit {
    require Pod::Usage;
    Pod::Usage::pod2usage( -verbose => 1 );
}


sub print_version_and_exit {
    require Pod::Usage;
    Pod::Usage::pod2usage(
        -verbose  => 99,
        -sections => 'VERSION|COPYRIGHT',
    );
}

__END__

=head1 NAME

munin-httpd - Runs a http server for displaying Munin graphs.

=head1 USAGE

munin-httpd [options]

=head1 REQUIRED ARGUMENTS

None.

=head1 EXIT STATUS

This daemon should normally not exit, non-zero on failure.

=head1 DESCRIPTION

munin-httpd is a simple http server to display Munin graphs.
It supports three click zooming.

=head1 OPTIONS

=over 5

=item B<< --listen <hostname:port> >>

Sets the hostname and port to listen on. [*:4948]

=item B<--help >

View this help message.

=item B<--version >

Show version information.

=back

=head1 VERSION

This is munin-httpd (munin) v@@VERSION@@

=head1 AUTHOR

Steve Schnepp

=head1 BUGS AND LIMITATIONS

None known. If you found one, please report under L<https://github.com/munin-monitoring/munin/issues>.

=head1 LICENSE AND COPYRIGHT

Copyright (C) 2014-2015 Steve Schnepp

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; version 2 dated June,
1991.

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/>.

=cut
