<?php
/*
  Copyright (C) 2020  Denver Gingerich <denver@ossguy.com>

  This file is part of sgx-bwmsgsv2.

  sgx-bwmsgsv2 is free software: you can redistribute it and/or modify it under
  the terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or (at your option) any
  later version.

  sgx-bwmsgsv2 is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
  details.

  You should have received a copy of the GNU Affero General Public License along
  with sgx-bwmsgsv2.  If not, see <http://www.gnu.org/licenses/>.
*/

$time = microtime(true);
$tai_timestamp = trim(shell_exec('./tai'));

$raw_data = file_get_contents('php://input');

# below must set $redis_host, $redis_port, $queue_name ($redis_auth is optional)
# *it is the settings file for this program, the bwmsgsv2 HTTP to Redis acceptor
include 'settings-h2r.php';

$redis = new Redis();
$rv = $redis->pconnect($redis_host, $redis_port);

if (!$rv) {
	error_log("ERROR 1a in Redis connect at $time - cannot save $raw_data");
	http_response_code(503);  # Service Unavailable
	exit(0);
}

if (!empty($redis_auth)) {
	# TODO: check return value to confirm login succeeded
	$redis->auth($redis_auth);
}

$time2 = microtime(true);
$tai_timestamp2 = trim(shell_exec('./tai'));

$rv = $redis->lPush('incoming_messages-'.$queue_name,
	'"ts_020_tai-first_db_hit":'.$tai_timestamp2.
	',"ts_020_unix-first_db_hit":'.$time2.
	',"ts_010_tai-first_received":'.$tai_timestamp.
	',"ts_010_unix-first_received":'.$time.',"MSG":'.$raw_data);

if (!$rv) {
	error_log("ERROR 2a in lPush at $time $time2 - cannot save $raw_data");
	http_response_code(503);  # Service Unavailable
	exit(0);
}

print 'ok';

?>
