#!/usr/bin/perl

use File::Basename;
use lib dirname (__FILE__);

use IO::Socket;
use NVPNConfig;

use constant {
        NVPN_IPTD_ACTION => "action",
        NVPN_IPTD_INTERNAL_IP => "internalip",
        NVPN_IPTD_EXTERNAL_IP => "externalip",
        NVPN_IPTD_REAL_IP => "realip",
        NVPN_IPTD_TYPE => "type",
        NVPN_IPTD_PORTS => "ports",
        NVPN_IPTD_FINISH => "exit"
};

sub nvpn_iptd_listforwards
{
	my %params = (
		&NVPN_IPTD_ACTION => "listforwards"
	);
	return nvpn_iptd_comm(\%params);
}

sub nvpn_iptd_register
{
	my ($internal, $external, $real, $type, $port) = @_;
	my %params = (
		&NVPN_IPTD_ACTION => "initclient",
		&NVPN_IPTD_INTERNAL_IP => $internal,
		&NVPN_IPTD_EXTERNAL_IP => $external,
		&NVPN_IPTD_REAL_IP => $real,
		&NVPN_IPTD_TYPE => $type
	);
	$params{&NVPN_IPTD_PORTS} = $port if ($port =~ /[\d ]+/);
	return nvpn_iptd_comm(\%params);
}

sub nvpn_iptd_unregister
{
	my ($internal, $real) = @_;
	my %params = (
		&NVPN_IPTD_ACTION => "removeclient",
		&NVPN_IPTD_INTERNAL_IP => $internal,
	);
	return nvpn_iptd_comm(\%params);
}

sub nvpn_iptd_comm
{
	my $params = shift;
	my $sockfd = nvpn_iptd_connect();
	nvpn_iptd_send($sockfd, $params);
	my $out = nvpn_iptd_read($sockfd);
	nvpn_iptd_disconnect($sockfd);
	return $out;
}

sub nvpn_iptd_send
{
	my ($sockfd, $params) = @_;
	while (($k, $v) = each($params)) {
		print $sockfd "$k=$v\n"; 
	}
	print $sockfd NVPN_IPTD_FINISH . "\n";
}

sub nvpn_iptd_read
{
	my $sockfd = shift;
	return $sockfd->getline();
}

sub nvpn_iptd_connect {
	return new IO::Socket::INET ( PeerAddr => IPTD_HOST, PeerPort => IPTD_PORT, Proto => IPTD_PROTO);
}

sub nvpn_iptd_disconnect
{
	my $sockfd = shift;
	close $sockfd;
}

#nvpn_iptd_register("10.223.72.1", "204.152.219.87", "static", "1 2 3 4");
#nvpn_iptd_unregister("10.223.72.1");

1;
