#
# EMG perl connector for receiving delivery reports from Hypermedia via HTTP API
# $Change: 43222 $
#

use strict;
use POSIX qw(strftime);

my $debug = 1;
my $logfile = "/tmp/hm-send.log";

sub handle_dlr {
	my ($ci, $arg) = @_;

	do_handle_dlr($ci, $arg);
}

sub do_handle_dlr {
	my ($ci, $arg) = @_;
	my $data = ${$arg}{'data'};
	my $op = ${$arg}{'operation'};
	my $cname = ${$ci}{'name'};

	if($debug) {
		dolog("do_handle_dlr: cname=$cname");
		dolog("do_handle_dlr: op=$op data=$data");
	}

	if($op eq '0') {
		# Pass 1 - Parse parameters
		my $params = parse_form_data($data);

		my $msg_id = $params->{'msg_id'};
		my $result = $params->{'result'};

		# Mandatory parameters missing?
		if($msg_id eq '' || $result eq '') {
			# Return fail
			${$arg}{'status'} = 500;
			return;
		}

		# Compose message
		my %message = ();
		$message{'origid'} = $msg_id;
		if($result eq 'OK') {
			$message{'messagestate'} = 'DELIVERED';
		} else {
			$message{'messagestate'} = 'FAILED';
		}
		${$arg}{'dlrs'} = \%message;

		# Return ok
		${$arg}{'status'} = 202;
		${$arg}{'data'} = '';
	} else {
		# Pass 2 - Finalize response to client
		${$arg}{'data'} = '';
	}
}

# Helper function for parsing form data
sub parse_form_data {
	my $data = shift;
	my @params = split(/&/, $data);      
	my $param_hash;
	foreach my $param (@params) {
		my($name, $value) = split (/=/, $param);
		$name =~ tr/+/ /;
		$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		$value =~ tr/+/ /;
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		$value =~s/<!--(.|\n)*-->//g;
		$param_hash->{$name} = $value;
	}
	return $param_hash;
}

sub dolog {
        my $str = shift;
	my $ts = strftime("%Y-%m-%d %H:%M:%S", localtime);
        open(OUT, ">>$logfile");
        print OUT "$ts $str\n";
        close(OUT);
}

1;
