#!/usr/bin/perl
#
# Copyright (C) 2010 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

use strict;
use warnings;

use English qw(-no_match_vars);
use Sys::Hostname;
use Data::Dumper;
use Getopt::Long;
use Pod::Usage;

use Munin::Node::SpoolReader;
use Munin::Node::SpoolWriter;
use Munin::Common::Defaults;
use Munin::Common::Logger;
use Munin::Common::Utils qw( is_valid_hostname );

# Disable buffering
$OUTPUT_AUTOFLUSH = 1;

my $SPOOLDIR = $Munin::Common::Defaults::MUNIN_SPOOLDIR;
my $hostname;
my $overridehost;

my $spoolfetch;
my $vectorfetch;
my $cleanup;
my $cleanupandexit;

my $verbose;
my $debug;
my $screen;
my $help;

GetOptions(
        "spooldir|s=s" => \$SPOOLDIR,
        "hostname=s" => \$overridehost,
        "cleanup" => \$cleanup,
        "cleanupandexit" => \$cleanupandexit,

        "spoolfetch" => \$spoolfetch,
        "vectorfetch" => \$vectorfetch,

        "help|h" => \$help,
        "verbose|v" => \$verbose,
        "debug" => \$debug,
        "screen" => \$screen,
) or pod2usage(1);
if ($help) {
        pod2usage(1);
}


if ($cleanupandexit) {
	cleanup();
	exit;
}

if ($overridehost) {
    if (! is_valid_hostname($overridehost)) {
        CRITICAL(sprintf("invalid hostname: %s\n", $overridehost));
        exit(65);
    }
}

if ( $verbose || $debug || $screen ) {
    my %log;
    $log{output} = 'screen' if $screen;
    $log{level}  = 'info'   if $verbose;
    $log{level}  = 'debug'  if $debug;
    Munin::Common::Logger::configure(%log);
}

# Use STDIN/STDOUT, in order to be:
# 1. secure over internet (SSH), munin-node needs only
#    to listen on localhost:4949
# 2. very simple to launch

my $spoolreader = Munin::Node::SpoolReader->new(
	spooldir => $SPOOLDIR,
);

$hostname = $spoolreader->get_metadata("hostname") || hostname();
$hostname = $overridehost if $overridehost;
chomp($hostname);

INFO("Starting");

print "# munin node at $hostname\n";

while (my $line = <>) {
	if ($line =~ m/^list/) {
		print $spoolreader->list();
	} elsif ($line =~ m/^config (\w+)/) {
		# XXX - Vector-fetching is disabled for now
		print ".\n";
	} elsif ($vectorfetch && $line =~ m/^fetch (\w+)/) {
		# Fetching all values since last time

		# XXX - Vector-fetching is disabled for now
		print ".\n";
	} elsif ($line =~ m/^spoolfetch (-?\d+)/) {
		my $last_epoch = $1;
		print $spoolreader->fetch($last_epoch);
		print ".\n";
	} elsif ($spoolfetch && $line =~ m/^cap/) {
		print "cap spool\n";
	} elsif ($line =~ m/^quit/) {
		last;
	} else {
		print "# Unknown command.\n";
	}
}

cleanup() if $cleanup;
exit;

sub cleanup {
	my $spoolwriter = Munin::Node::SpoolWriter->new(
		spooldir => $SPOOLDIR,
	);
	$spoolwriter->cleanup();
}

__END__

=head1 NAME

munin-async - A program to replay spooled munin-node calls

=head1 SYNOPSIS

munin-async [options]

 Options:
     -s --spooldir <spooldir>   Directory for spooled data [@@SPOOLDIR@@]
     --hostname <hostname>      Overrides the hostname [`hostname`]
     --cleanup                  Clean up the spooldir after interactive session completes
     --cleanupandexit           Clean up the spooldir and exit (non-interactive)

     --spoolfetch               Enables the "spool" capability [no]
     --vectorfetch              Enables the "vectorized" fetching capability [no]
                                  Note that without this flag, the "fetch"
				  command is disabled.

     --screen                   Log to screen instead of syslog
     --debug                    Log debug messages
     -v --verbose               Be verbose
     -h --help                  View this message

