#!/usr/bin/perl -w 
#
# Zymonic Business Process and Information Management System
# Copyright Zednax Limited 2008 -
# For Authors and Changelog see the subversion history
use strict;

package main;

use Zymonic::Config;
use Zymonic::Decryptor::Client;

# Library path
BEGIN
{
    use Zymonic::Utils qw(clean debug death_handler get_array rethrow_exception);
    $main::SIG{__DIE__} = \&death_handler;
    no warnings;
    $SIG{CHLD}  = 'IGNORE';
    $SIG{CHILD} = 'IGNORE';    # Second instance for Solaris compatibility
    use warnings;
    $| = 1;
}

my $config_file = $ARGV[0];

unless ($config_file)
{
    print "Usage: send_keys.pl [config file]\n";
    exit;
}

my $config = load_config($config_file);

$Zymonic::system = $config->{system};

$Zymonic::ZCONFIG{$Zymonic::system} =
  Zymonic::Config->new( system_name => $Zymonic::system, config_dir => "/etc/zymonic", );

my $zdc = Zymonic::Decryptor::Client->new(
    config => $Zymonic::ZCONFIG{$Zymonic::system},
    db     => $Zymonic::ZCONFIG{$Zymonic::system}->{DB}
);

foreach my $kp ( 1, 2 )
{
    foreach my $key ( 'a', 'b' )
    {
        my $response = $zdc->call_decryptor(
            {
                messagetype     => 'SendKEKPart',
                username        => $config->{$kp}->{username},
                kek_part_number => $kp,
                kek_parts       => { $key => $config->{$kp}->{$key} },
            },
            'all', 'nokey'
        );

        print "KEY $key PART $kp RESPONSE: " . ( $response->{ok} ? 'OK' : $response->{error} ) . "\n";
    }
}

sub load_config
{
    my $config_file = shift;

    open( CF, '<', $config_file ) or die 'Can not open config file';

    my $conf_data = '';

    while (<CF>)
    {
        $conf_data .= $_;
    }

    $conf_data =~ s/;//g;

    my $config;

    eval '$config = ' . $conf_data;

    return $config;
}
