#!/usr/bin/perl
#
################################################################################
#
# IPCop Web-Iface for Munin
#
# Copyright (C) 2007 Olaf (weizen_42) Westrik
#
# 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; either version 2 of the License, or (at your option) any later version. 
#
# 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 St, Fifth Floor, Boston, MA 02110, USA 
#
#
# Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation veröffentlicht, weitergeben und/oder modifizieren, entweder gemäß Version 2 der Lizenz oder (nach Ihrer Option) jeder späteren Version. 
#
# Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von Nutzen sein wird, aber OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie der MARKTREIFE oder der VERWENDBARKEIT FÜR EINEN BESTIMMTEN ZWECK. Details finden Sie in der GNU General Public License. 
#
# Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem Programm erhalten haben. Falls nicht, schreiben Sie an die Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA.
#
################################################################################
#
# For support post / read in http://www.ipcop-forum.de
#
# $Id: muningui.cgi 250 2007-10-08 06:31:36Z weizen_42 $
#
# 2007-07 created by weizen_42
#

use strict;

# enable only the following on debugging purpose
use warnings;
use CGI::Carp 'fatalsToBrowser';

use LWP::UserAgent;

require '/var/ipcop/general-functions.pl';
require '/var/ipcop/lang.pl';
require '/var/ipcop/header.pl';

my $version = 'v0.3.1';
my $debug = 0;
my $errormessage = '';
# checking for new version
my $addonname = 'munin';
my $onlineversion = '';
my $onlinelink = '';
my $timestamplastcheck = '/var/ipcop/munin/lastcheck';
my $flagdonotcheck = '/var/ipcop/munin/noversioncheck';

my $option_table = '';

my %selected=();
my %hashcgi=();
$hashcgi{'ACTION'} = '';
$hashcgi{'SERVER_IP'} = '';
$hashcgi{'LOGLEVEL'} = '4';
my %hashsettings = ();
$hashsettings{'SERVER_IP'} = '';
$hashsettings{'LOGLEVEL'} = '4';

&Header::getcgihash(\%hashcgi);
&General::readhash('/var/ipcop/munin/settings', \%hashsettings);


&Header::showhttpheaders();

&Header::openpage('Munin', 1, '');
&Header::openbigbox('100%', 'left');


if ( $hashcgi{'ACTION'} eq "$Lang::tr{'save'}" ) 
{
  unless( &General::validip($hashcgi{'SERVER_IP'}) )
  {
    $errormessage = $Lang::tr{'munin error ip'};
    goto ERROREXIT;
  }

  $hashsettings{'SERVER_IP'} = $hashcgi{'SERVER_IP'};
  $hashsettings{'LOGLEVEL'} = $hashcgi{'LOGLEVEL'};
  &General::writehash('/var/ipcop/munin/settings', \%hashsettings);
  &WriteConfig_munin_conf();
#  system("/usr/local/bin/muninctrl restart >/dev/null");
  system("/usr/local/bin/muninctrl restart >/dev/null 2>&1 &");
}
ERROREXIT:


if ( $errormessage )
{
  &Header::openbox('100%', 'left', $Lang::tr{'error messages'});
  print "<class name='base'>$errormessage\n";
  print "&nbsp;</class>\n";
  &Header::closebox();
}


# Found this usefull piece of code in BlockOutTraffic AddOn  8-)
#   fwrules.cgi
###############
# DEBUG DEBUG
if ( $debug )
{
&Header::openbox('100%', 'left', 'DEBUG');
my $debugCount = 0;
foreach my $line (sort keys %hashcgi) {
  print "$line = $hashcgi{$line}<br />\n";
  $debugCount++;
}
print "&nbsp;Count: $debugCount\n";
&Header::closebox();
}
# DEBUG DEBUG
###############


#
# Check for new version
#
&checkfornewversion($addonname, $version);
if ( $onlineversion ne '' )
{
  &Header::openbox('100%', 'left', $Lang::tr{'info'});
  print <<END
<table width="100%"><tr>
<td>$Lang::tr{'munin newversion'} <a href="$onlinelink" target="_blank"><b>$onlineversion</b></a></td>
</tr></table>
END
;
  &Header::closebox();
}

$selected{'LOGLEVEL'}{'0'} = '';
$selected{'LOGLEVEL'}{'1'} = '';
$selected{'LOGLEVEL'}{'2'} = '';
$selected{'LOGLEVEL'}{'3'} = '';
$selected{'LOGLEVEL'}{'4'} = '';
$selected{'LOGLEVEL'}{$hashsettings{'LOGLEVEL'}} = "selected='selected'";

&Header::openbox('100%', 'left', 'Munin');

print <<END
<form method='post' action='$ENV{'SCRIPT_NAME'}'><table width='100%'>
<tr><td width='30%' class='base'>$Lang::tr{'munin server ip'}:</td><td><input type='text' name='SERVER_IP' value='$hashsettings{"SERVER_IP"}' size='18' /></td></tr>
<tr><td width='30%' class='base'>Loglevel:</td><td>
    <select name='LOGLEVEL'>
      <option value='0' $selected{'LOGLEVEL'}{'0'}>0 (off)</option>
      <option value='1' $selected{'LOGLEVEL'}{'1'}>1</option>
      <option value='2' $selected{'LOGLEVEL'}{'2'}>2</option>
      <option value='3' $selected{'LOGLEVEL'}{'3'}>3</option>
      <option value='4' $selected{'LOGLEVEL'}{'4'}>4 (full)</option>
    </select></td>
</td></tr>
</table>
<hr /><table width='100%'>
<tr>
  <td width='55%' class='base' valign='top'>&nbsp;</td>
  <td width='40%' align='center'><input type='submit' name='ACTION' value='$Lang::tr{'save'}' /></td>
  <td width='5%' align='right'>&nbsp;</a></td>
</tr>
</table>
<hr />
<table width='100%'>
<tr>
  <td>&nbsp;</td>
  <td align='right'>
  <b><small><a href="http://www.ban-solms.de/t/IPCop.html" target="_blank">Munin Addon $version</a></small></b>
  </td>
</tr>
</table>
</form>
END
;
&Header::closebox();

&Header::closebigbox();
&Header::closepage();


sub checkfornewversion
{
  my $addon = shift;
  my $version = shift;
  $onlineversion = '';

  if ( -e $flagdonotcheck )
  {
    return;
  }

  # only check if we are online and last check was some time ago
  if ( (! -e '/var/ipcop/red/active') || (-e $timestamplastcheck) && (int(-M $timestamplastcheck) < 5) )
  {
    return;
  }

#workaround to suppress a warning when a variable is used only once
  my @dummy = ( $General::version );
  undef (@dummy);

  my $ua = LWP::UserAgent->new;
  $ua->timeout(120);
  $ua->agent("Mozilla/4.0 (compatible; IPCop $General::version; $version)");
  my $content = $ua->get("http://ipcop-addons.ath.cx/version/$addon");

  if ( $content->is_success )
  {
    # compare the versions, format is v1.2.3
    $content->content =~ /v(\d+).(\d+).(\d+)/;
    my $ver1 = $1;
    my $ver2 = $2;
    my $ver3 = $3;

    $version =~ /v(\d+).(\d+).(\d+)/;

    if ( ($ver1 > $1) || (($ver1 == $1) && ($ver2 > $2)) || (($ver1 == $1) && ($ver2 == $2) && ($ver3 > $3)) )
    {
      $onlineversion = "v$ver1.$ver2.$ver3";

      $content->content =~ /http(.*)/;
      $onlinelink = "http$1";
    }
    else
    {
      # no news, recheck in a couple of days
      system("touch $timestamplastcheck");
    }
  }
}


sub WriteConfig_munin_conf
{
  open (CONFIGFILE, ">/var/ipcop/munin/munin-node.conf");
  print CONFIGFILE <<END

#
# config-file for munin-node written by IPCop Munin Addon
#

log_level $hashsettings{'LOGLEVEL'}
log_file /var/log/munin-node.log
port 4949
pid_file /var/run/munin-node.pid
background 1
setseid 1

# Which port to bind to;
host *
user root
group root
setsid yes

default_plugin_group root

# Regexps for files to ignore

ignore_file ~\$
ignore_file \\.bak\$
ignore_file %\$
ignore_file \\.dpkg-(tmp|new|old|dist)\$
ignore_file \\.rpm(save|new)\$

# Set this if the client doesn't report the correct hostname when
# telnetting to localhost, port 4949
#
#host_name localhost.localdomain

# A list of addresses that are allowed to connect.  This must be a
# regular expression, due to brain damage in Net::Server, which
# doesn't understand CIDR-style network notation.  You may repeat
# the allow line as many times as you'd like

allow ^127\\.0\\.0\\.1\$
END
;

  if ( $hashsettings{'SERVER_IP'} ne '' )
  {
    $hashsettings{'SERVER_IP'} =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
    print CONFIGFILE "allow ^$1\\.$2\\.$3\\.$4\$\n";
  }

  close CONFIGFILE;
}
