# --
# Kernel/System/Ticket/Event/NagiosAcknowledge.pm - acknowlege nagios tickets
# Copyright (C) 2001-2010 OTRS AG, http://otrs.org/
# --
# $Id: NagiosAcknowledge.pm,v 1.9 2010/02/15 18:16:06 ub Exp $
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (AGPL). If you
# did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
# --

package Kernel::System::Ticket::Event::ZabbixAcknowledge;

use strict;
use warnings;
use JSON;
use JSON::RPC::Client;

use vars qw($VERSION);
$VERSION = qw($Revision: 1.9 $) [1];

sub new {
    my ( $Type, %Param ) = @_;

    # allocate new hash for object
    my $Self = {};
    bless( $Self, $Type );

    # get needed objects
    for (
        qw(ConfigObject TicketObject LogObject UserObject CustomerUserObject SendmailObject TimeObject EncodeObject UserObject)
        )
    {
        $Self->{$_} = $Param{$_} || die "Got no $_!";
    }

    # get correct FreeFields
    $Self->{Fevent}    = $Self->{ConfigObject}->Get('Zabbix::Acknowledge::FreeField::Event');

    return $Self;
}

sub Run {
    my ( $Self, %Param ) = @_;

    # check needed stuff
    for (qw(TicketID Event Config)) {
        if ( !$Param{$_} ) {
            $Self->{LogObject}->Log( Priority => 'error', Message => "Need $_!" );
            return;
        }
    }
    
    # Set UserID to root if we didn't get it
    my $UserID = 1;
    if ($Param{UserID}){
	$UserID = $Param{UserID};
    };

    # check if acknowledge is active
    my $Enable = $Self->{ConfigObject}->Get('Zabbix::Acknowledge::Enable');
    if (!$Enable){
	$Self->{LogObject}->Log( Priority => 'debug', Message => "Zabbix acknowledge not enabled" );
	return 1;
    };

    # check if it's a Zabbix related ticket
    my %Ticket = $Self->{TicketObject}->TicketGet( TicketID => $Param{TicketID} );
    if ( !$Ticket{ $Self->{Fevent} } ) {
        $Self->{LogObject}->Log( Priority => 'debug', Message => "No Event ID in the ticket!" );
        return 1;
    }
    
    # Get ticket event ID
    $Self->{EventID} = $Ticket{$Self->{Fevent}};
    
    my $Msg   = $Self->{ConfigObject}->Get('Zabbix::Acknowledge::Message');

    # replace ticket tags
    for my $Key ( keys %Ticket ) {
        next if !defined $Ticket{$Key};

        # strip not allowd chars
        $Ticket{$Key} =~ s/'//g;
        $Ticket{$Key} =~ s/;//g;
        $Msg          =~ s/<$Key>/$Ticket{$Key}/g;
    }

    # replace config tags
    $Msg =~ s{<CONFIG_(.+?)>}{$Self->{ConfigObject}->Get($1)}egx;
    
    # Replace newlines
    

    my $Return = $Self->_JSON_Zabbix(Ticket => \%Ticket, Message => "$Msg");

    if (!$Return) {
        $Self->{TicketObject}->HistoryAdd(
            TicketID     => $Param{TicketID},
            HistoryType  => 'Misc',
            Name         => "Sent Acknowledge to Zabbix.",
            CreateUserID => $UserID,
        );
        return;
    }
    else {
        $Self->{TicketObject}->HistoryAdd(
            TicketID     => $Param{TicketID},
            HistoryType  => 'Misc',
            Name         => "Was not able to send Acknowledge to Zabbix!",
            CreateUserID => $UserID,
        );
        return 1;
    }
    return;
}

sub _JSON_Zabbix {
    my ( $Self, %Param ) = @_;

    # check needed stuff
    for (qw(Ticket Message)) {
        if ( !$Param{$_} ) {
            $Self->{LogObject}->Log( Priority => 'error', Message => "Need $_!" );
            return 1;
        }
    }
    # Get parameters
    my %Ticket = %{ $Param{Ticket} };
    my $URL   = $Self->{ConfigObject}->Get('Zabbix::Acknowledge::HTTP::URL');
    
    
    # RPC start
    my $id=0;
    my $rpc = new JSON::RPC::Client;
    
    # Auth first
    $id = $id + 1;
    my $auth = {
	'jsonrpc' => '2.0',
	'method' => 'user.authenticate',
	'id' => $id,
	'params' => {
	    'user' => $Self->{ConfigObject}->Get('Zabbix::Acknowledge::HTTP::User'),
	    'password' => $Self->{ConfigObject}->Get('Zabbix::Acknowledge::HTTP::Password'),
	},
    };
    my $rpc_result=$rpc->call($URL, $auth);
    if ($rpc_result->is_error){
        $Self->{LogObject}->Log(
            Priority => 'error',
            Message  => "Can't authenticate $URL: " . "$rpc_result->jsontext",
        );
        return 1;
    };
    # Get auth hash
    $auth = $rpc_result->result;
    
    # Post RPC query and get result
    $id = $id + 1;
    my $request = {
	'jsonrpc' => '2.0',
	'method' => 'event.acknowledge',
	'id' => $id,
	'params' => {
	    'eventids' => [ "$Self->{EventID}" ],
	    'message' => "$Param{Message}"
	},
        'auth' => $auth,
    };
    $rpc_result=$rpc->call($URL, $request);
    if ($rpc_result->is_error){
        $Self->{LogObject}->Log(
            Priority => 'error',
            Message  => "Can't request $URL: " . "$rpc_result->jsontext",
        );
        return 1;
    };
    return;
}
1;
