#!/usr/bin/perl

use strict;
use warnings;

use IO::Socket::IP;
use Getopt::Long;
use Config::Tiny;

my $ip;
my $port;
my $conffile = '/etc/rtpengine/rtpengine.conf';
my $listen;
my $help;

Getopt::Long::Configure('require_order');

my $optret = GetOptions(
    'help|h'              => \$help,
    'ip=s'                => \$ip,
    'port=i'              => \$port,
    'config-file=s'       => \$conffile,
);

if (-f $conffile) {
    my $config = Config::Tiny->read($conffile);
    $config or die "Failed to read config file: " . Config::Tiny->errstr;

    $listen = $config->{rtpengine}{'listen-cli'}
        if $config->{rtpengine};
    if ($listen =~ /^\d+$/) {
        $port //= $listen;
    }
    else {
        $ip //= $listen;
    }
}

if ($ip && $ip =~ s/:(\d+)$// && !$port) {
    $port = $1;
}

my $argumentstring = "@ARGV";
$argumentstring = trim($argumentstring);

$ip //= '127.0.0.1';
$port //= 9900;

if ($help || !$argumentstring || !$optret || $port <= 0 || $port > 65535) {
    $argumentstring = 'usage';

    print "\n";
    print "    rtpengine-ctl [ -ip <ipaddress>[:<port>] -port <port> ] <command>\n";
    print "\n";
}

# create a connecting socket
my $socket = IO::Socket::IP->new(
    PeerHost => $ip,
    PeerPort => $port,
    Proto => 'tcp',
);
die "Cannot connect to rtpengine $!\n" unless $socket;

$socket->autoflush(1);

#set send/recv timeout so script doesn't hang when rtpengine doesn't interact
setsockopt($socket, SOL_SOCKET, SO_SNDTIMEO, pack('L!L!', 3, 0) ) or die $!;
setsockopt($socket, SOL_SOCKET, SO_RCVTIMEO, pack('L!L!', 3, 0) ) or die $!;

my $size = $socket->send("$argumentstring\n");
 
# receive a response of up to 10MB
my $response = "";

do {
   $response = "";
   $socket->recv($response, 1024*1024*10);
   print $response; 
} while ( not $response eq "");

$socket->close();

sub  trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };
