#!/usr/bin/env ruby
#
# 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/>.

require 'redis'
require 'hiredis'
require 'net/http'
require 'time'

$stdout.sync = true

puts "Redis queue to SGX HTTP request translator - for Bandwidth API V2 SGX\n"\
	"==>> last commit of this version is " + `git rev-parse HEAD` + "\n"

if ARGV.size != 3
	# note that <redis_queue_suffix> should match h2r-bwmsgsv2's $queue_name
	puts "Usage: r2s-bwmsgsv2.rb <redis_queue_suffix> <sgx_hostname> "\
		"<sgx_https_port>"
	exit 0
end

["INT", "TERM"].each do |sig|
	trap(sig) do
		puts "Translator has terminated due to SIG#{sig}."
		exit 0
	end
end

t = Time.now
puts "LOG %d.%09d: starting...\n\n" % [t.to_i, t.nsec]

redis = Redis.new(driver: :hiredis)

pending_len = redis.llen('pending_messages-' + ARGV[0])
if pending_len != 0
	puts 'Translator terminated due to non-empty pending queue of size ' +
		pending_len.to_s
	exit 1
end

loop do
	timestamps_plus_json_blob = redis.brpoplpush('incoming_messages-' +
		ARGV[0], 'pending_messages-' + ARGV[0])

	t = Time.now
	ts = "%d.%09d" % [t.to_i, t.nsec]
	tai_timestamp = `./tai`.strip
	tai_yyyymmdd = Time.at(tai_timestamp.to_i).strftime('%Y%m%d')
	puts "LOG %s, %s: handling message sent on %s ...\n" %
		[ts, tai_timestamp, tai_yyyymmdd]

	# WARNING: since not atomic with setex() below, translator is singleton
	day_msg_count = redis.incr(
		"archived_message-#{ARGV[0]}-#{tai_yyyymmdd}-total"
	)
	# TODO: confirm day_msg_count is integer > 0 (otherwise likely an error)
	#  unsure how to best error here: bail would cause infinite bounce; eml?

	t = Time.now
	puts "LOG %d.%09d: total msgs for %s-%s now at %s\n" %
		[t.to_i, t.nsec, tai_yyyymmdd, ARGV[0], day_msg_count]

	# TODO: print less stuff in here
	puts "TODO - got some stuff: " + timestamps_plus_json_blob
	puts "TODO - daymsgcount: '#{day_msg_count}'"

	t2 = Time.now
	ts2 = "%d.%09d" % [t2.to_i, t2.nsec]
	tai_timestamp2 = `./tai`.strip

	new_json_blob =
		'"ts_040_tai-translator_pre_send":' + tai_timestamp2 +
		',"ts_040_unix-translator_pre_send":' + ts2 +
		',"ts_030_tai-translator_received":' + tai_timestamp +
		',"ts_030_unix-translator_received":' + ts +
		',' + timestamps_plus_json_blob

	uri = URI("http://#{ARGV[1]}:#{ARGV[2]}/")
	req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
	req.body = new_json_blob.split('G', 2)[1][2..-1] # only use MSG part
	begin
		res = Net::HTTP.start(uri.hostname, uri.port) do |http|
			http.request(req)
		end
	# list of exceptions is from https://stackoverflow.com/a/5370726
	rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
	       Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError,
	       Net::ProtocolError => e

		puts "TODO problem '#{e}' - now we should try again..."
		# TODO: actually try again
	else
		puts "TODO - res: '#{res.code}' '#{res.message}': '#{res.body}'"
	end

	# TODO: add following functionality:
	# if SGX gives back anything but response.code 200, retry 5 times-ish
	# if SGX failed to respond after retries, email or other notify
	#  and back off with even longer retries (can't do anything else really)

	exists = redis.exists(
		"archived_message-#{ARGV[0]}-#{tai_yyyymmdd}-#{day_msg_count}"
	)
	if exists
		puts 'Translator terminated since archive message at index ' +
			day_msg_count.to_s + ' for day ' + tai_yyyymmdd.to_s +
			" unexpectedly exists already, with retval '#{exists}'"
		exit 2
	end

	# WARNING: since not atomic with incr() above, translator is singleton
	rv1 = redis.setex(
		"archived_message-#{ARGV[0]}-#{tai_yyyymmdd}-#{day_msg_count}",
		259200, new_json_blob
	)
	if rv1 != 'OK'
		puts 'Translator terminated since archive message at index ' +
			day_msg_count.to_s + ' for day ' + tai_yyyymmdd.to_s +
			" could not be saved, with return value '#{rv1}'"
		exit 3
	end

	pending_len = redis.llen('pending_messages-' + ARGV[0])
	if pending_len != 1
		puts 'Translator terminated since pending queue (at index ' +
			day_msg_count.to_s + ' for day ' + tai_yyyymmdd.to_s +
			') has unexpected non-1 length of ' + pending_len.to_s
		exit 4
	end

	pending_item = redis.rpop('pending_messages-' + ARGV[0])
	if timestamps_plus_json_blob != pending_item
		puts 'Translator terminated since archived item (at index ' +
			day_msg_count.to_s + ' for day ' + tai_yyyymmdd.to_s +
			") does not match pending item '#{pending_item}'"
		exit 5
	end
end
