#!/usr/bin/perl

use warnings;
use strict;

use Getopt::Std;
use Config::General;
use IO::Poll;
use HTTP::Daemon::SSL;
use HTTP::Request::Params;
use LWP::UserAgent;
use URI;
use MIME::Base64;
use Data::Dumper;
use Sys::Syslog qw(:DEFAULT setlogsock :macros);
use POSIX ":sys_wait_h";
use JSON;
use vars qw/ %opts /;

my $appname = "backend_voipms";
my $version = "0.0.2";
my $loglevel = 1;
my $confpath = "/etc/xmppipe_voipms.conf";
my $api_url = "https://voip.ms/api/v1/rest.php";
my %conf;
my $debug = 0;

our $opts;

sub logger
{
	my ($level, @args) = @_;
	my $message = join("", @args);

	if ($debug == 1) {
		print(STDERR "$appname: $message\n");
	} else {
		syslog($level, $message);
	}
}

sub log_fatal
{
	my $msg = shift;
	logger("crit", $msg);
	exit(1);
}

sub load_config
{
	my $config = new Config::General(-ConfigFile => $confpath,
		-LowerCaseNames => 1, -AutoTrue => 1) or
		log_fatal("failed to load config $confpath");
	%conf = $config->getall();
	$loglevel = $conf{'log_level'} if (defined($conf{'log_level'}));
}

sub usage
{
	print("Usage: $appname [-hdv]\n");
	print("\t-d\t\tdebug (print errors to STDERR, stays in foreground)\n");
	print("\t-c <path>\tspecify an alternate config path\n");
	print("\t-v\t\tprint version\n");
	print("\t-h\t\tprints this help\n");
}

sub voipms_send
{
	my $j = shift;

	if (!defined($j->{'to'})) {
		logger("err", "'to' not defined");
		return;
	}

	if (!defined($j->{'from'})) {
		logger("err", "'from' not defined");
		return;
	}

	if (!defined($j->{'body'})) {
		logger("err", "'body' not defined");
		return;
	}

	if ($j->{'body'} eq "") {
		logger("warning", "'body' empty, not sending");
		return;
	}

	my $url = URI->new($api_url);

	my $dst = $j->{'to'};
	$dst =~ s/\+1([0-9]+)@.*/$1/;

	# If we are sending a file, 'body' will contain a single URL
	# TODO: we may want to handle different DIDs here
	my $is_mms = 0;
	if ($j->{'body'} =~ /^https:\/\/[^ ]+$/) {
		$is_mms = 1;
		$url->query_form(
			'api_username' => $conf{'api_username'},
			'api_password' => $conf{'api_password'},
			'did' => $conf{'my_did'},
			'dst' => $dst,
			'message' => 'media',
			'media1' => $j->{'body'},
			'method' => 'sendMMS'
		);
	} elsif (length($j->{'body'}) > 140) {
		$is_mms = 1;
		$url->query_form(
			'api_username' => $conf{'api_username'},
			'api_password' => $conf{'api_password'},
			'did' => $conf{'my_did'},
			'dst' => $dst,
			'message' => $j->{'body'},
			'method' => 'sendMMS'
		);
	} else {
		$url->query_form(
			'api_username' => $conf{'api_username'},
			'api_password' => $conf{'api_password'},
			'did' => $conf{'my_did'},
			'dst' => $dst,
			'message' => $j->{'body'},
			'method' => 'sendSMS'
		);
	}

	my $ua = LWP::UserAgent->new();
	$ua->agent('XMPPIPE/1.0');

	my $req = new HTTP::Request(
		'GET', $url,
		['Accept' => '*/*']
	);

	my $pid = fork();
	if (!defined($pid)) {
		logger("err", "fork(): $!");
		return;
	} elsif ($pid > 0) {
		return;
	}

	my $resp = $ua->request($req);
	if (!$resp->is_success()) {
		logger("err", "failed sending message: " .
			$resp->decoded_content);
		exit(1);
	}

	my $resp_j;
	eval {
		logger("debug", "Send response content: " . $resp->content);
		$resp_j = from_json($resp->content);
		if ($resp_j->{'status'} ne "success") {
			logger("err", "error: voip.ms status " .
				$resp_j->{'status'});
			exit(1);
		}
		if ($is_mms == 1) {
			logger("info", "MMS ID " . $resp_j->{'mms'} .
				" sent successfully");
		} else {
			logger("info", "SMS ID " . $resp_j->{'sms'} .
				" sent successfully");
		}
	} or do {
		logger("err", "bad JSON reply from voip.ms");
		exit(1);
	};

	exit(0);
}

sub http_accept
{
	my $h = shift;
	my $http = shift;
	my $c = $h->accept();
	if (!defined($c)) {
		return if ($!{EINTR});
		if ($!{ECONNABORTED}) {
			logger("err", "connection aborted while while accept()'ing");
			return;
		}
		my $errmsg = ($! eq "") ? IO::Socket::SSL::errstr() : $!;
		logger("err", "accept: $errmsg");
		return;
	};

	logger("info", "connection from " . $c->peerhost());

	pipe(my $rh, my $wh) or do {
		logger("err", "pipe: $!");
		return;
	};
	$wh->autoflush(1);

	my $pid = fork();
	if (!defined($pid)) {
		logger("err", "fork(): $!");
		close($wh);
		close($rh);
		close($c);
		return;
	} elsif ($pid == 0) {
		close($rh);
		handle_client($c, $wh);
		exit(0);
	}
	close($wh);
	$c->close(SSL_no_shutdown => 1);
	return $rh;
}

sub check_auth
{
        my ($http_connection, $req) = @_;

        my $auth = $req->header("Authorization");
        if ($auth) {
                $auth =~ s/Basic ([a-zA-Z0-9\+_=]+)/$1/;
                my ($user, $pw) = split(/:/, decode_base64($auth));
                if ($user eq $conf{'authuser'} && $pw eq $conf{'authpass'}) {
                        return 1;
                }
        }

        my $resp = new HTTP::Response(
                401,
                "Authorization Required",
                [
                        "Content-Type" => "text/html; charset=ascii",
                        "WWW-Authenticate" => "Basic realm=\"Pita\""
                ],
                "Authorization Required\n");
        $http_connection->send_response($resp);
        logger("notice", "sending auth request");
        return 0;
}

sub handle_client
{
	my ($http_connection, $pipe) = @_;
	my $resp;

	while (my $req = $http_connection->get_request) {
		if ($req->url->path ne '/message') {
			my $peer = $http_connection->peerhost();
			logger("notice", "client $peer: invalid request " .
				$req->url->path);
			$resp = new HTTP::Response(
				404,
				"Invalid request",
				[ "Content-Type" => "text/html; charset=ascii" ],
				"Invalid request\n");
			$http_connection->send_response($resp);
			next;
		}

		next if (!check_auth($http_connection, $req));

		my $parser = HTTP::Request::Params->new({
			req => $req,
		});

		my $r_content = $parser->params;
		logger("debug", "Request params: " . Dumper($r_content));

		if (!defined($r_content->{'from'}) || !defined($r_content->{'to'})) {
			my $peer = $http_connection->peerhost();
			logger("notice",
				"client $peer: missing to/from from request");
			$resp = new HTTP::Response(
				404,
				"Invalid request",
				[ "Content-Type" => "text/html; charset=ascii" ],
				"Invalid request\n");
			$http_connection->send_response($resp);
			next;
		}

		my $content = {};

		$content->{'to'} = $conf{'my_jid'};
		$content->{'from'} = "+1" . $r_content->{'from'} . "@" . $conf{'my_domain'};

		if (defined($r_content->{'message'})) {
			$content->{'body'} = $r_content->{'message'};
			logger("debug", "forwarding to XMPP: " . Dumper($content));
			print($pipe to_json($content, {pretty => 1}));
		}

		if (defined($r_content->{'media'})) {
			# voip.ms sends us media in a single 'media' arg, with
			# comma-separate URLs
			my @media = split(/,/, $r_content->{'media'});
			for my $m (@media) {
				$content->{'body'} = $m;
				logger("debug", "forwarding to XMPP: " .
					Dumper($content));
				print($pipe to_json($content, {pretty => 1}));
			}
		}

		$resp = new HTTP::Response(
			200,
			"OK",
			[ "Content-Type" => "text/plain" ],
			"ok");
		$http_connection->send_response($resp);
	}
	$http_connection->close();
}

sub main
{
	getopts("hdvc:", \%opts) or do {
		usage();
		exit(1);
	};

	if (defined($opts{'h'})) {
		usage();
		exit(0);
	}

	if (defined($opts{'v'})) {
		print("$appname version $version\n");
		exit(0);
	}

	if (defined($opts{'d'})) {
		$debug = 1;
	}

	if (defined($opts{'c'})) {
		$confpath = $opts{'c'};
	}

	load_config();

	openlog($appname, "ndelay,nofatal,pid", "daemon");
	if ($debug == 0) {
		if ($loglevel == 0) {
			setlogmask(LOG_UPTO(LOG_ERR));
		} elsif ($loglevel == 1) {
			setlogmask(LOG_UPTO(LOG_INFO));
		} else {
			setlogmask(LOG_UPTO(LOG_DEBUG));
		}
	}

	my $http = HTTP::Daemon::SSL->new(
		Listen => 5,
		ReuseAddr => 1,
		SSL_key_file => $conf{'key'},
		SSL_cert_file => $conf{'cert'},
		LocalAddr => $conf{'listen_address'},
		LocalPort => $conf{'listen_port'}) or do {
		log_fatal("HTTP daemon creation failed: $!");
	};

	logger("notice", "listening on port " . $conf{'listen_address'} .
		":" . $conf{'listen_port'});

	my $poll = IO::Poll->new();
	$poll->mask($http => POLLIN);
	$poll->mask(\*STDIN => POLLIN);

	my $json_from_xmpp = JSON->new();
	my $json_from_backend = JSON->new();
	$| = 1;
	my $shutdown = 0;
	while ($shutdown == 0) {
		while ((my $pid = waitpid(-1, WNOHANG)) > 0) {
			my $st = ($? >> 8);
			logger("info", "child $pid exited ($st)");
		}

		if ($poll->poll(0.1) == -1) {
			next if $!{EINTR};
			log_fatal("poll: $!");
		}

		for my $h ($poll->handles(POLLIN|POLLERR|POLLHUP|POLLNVAL)) {
			if ($h eq $http) {
				my $rh = http_accept($http, $h);
				next if (!defined($rh));
				$poll->mask($rh => POLLIN);
			} elsif ($h eq \*STDIN) {
				my $buf;
				my $r = sysread(STDIN, $buf, 4096);
				if (!defined($r)) {
					next if $!{EINTR};
					$poll->remove($h);
					$shutdown = 1;
					logger("err", "failed reading " .
						"from stdin: $!");
					next;
				} elsif ($r == 0) {
					$poll->remove($h);
					$shutdown = 1;
					next;
				}

				eval {
					$json_from_xmpp->incr_parse($buf);
					while (my $j = $json_from_xmpp->incr_parse()) {
						voipms_send($j);
					}
				} or do {
					logger("err", "bad JSON from xmppipe");
					next;
				};
			} else {
				# Any other HTTP client
				my $rbuf;
				my $r = sysread($h, $rbuf, 4096);
				if (!defined($r) || $r == 0) {
					if (!defined($r)) {
						next if $!{EINTR};
						logger("err", "failed reading" .
							" from http child: $!");
					}
					$poll->remove($h);
					close($h);
					next;
				}
				eval {
					$json_from_backend->incr_parse($rbuf);
					while (my $j = $json_from_backend->incr_parse()) {
						print(to_json($j, {pretty => 1}));
					}
				} or do {
					logger("err", "bad JSON from client");
					next;
				};
			}
		}
	}
}

main();
exit(0);
