#!/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 'json'
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)

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

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

	day_msg_count = redis.incr(
		"archived_message-#{ARGV[0]}-#{tai_yyyymmdd}-total"
		).then { |total|

		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], total]
	}

	# TODO: do something with day_msg_count

	# TODO: print less stuff in here
	puts "TODO - got some stuff: " + timestamps_plus_json_blob

	# add some timestamps to timestamps_plus_json_blob (our own)

	# TODO: fix so sending timestamps_plus_json_blob to SGX, and via POST
	response = Net::HTTP.get_response(
		URI("https://#{ARGV[1]}:#{ARGV[2]}/r2tst.php")
	)

	puts "TODO - response.code = #{response.code} and body #{response.body}"

	# 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)

	# if got HTTP 200, then:

	# redis.set(...) with expiration of 3 days, including timestamps
	#  use key: archived_message-#{ARGV[0]}-#{tai_yyyymmdd}-#{day_msg_count}

	# confirm pending key has one element and e == timestamps_plus_json_blob
	#  if so, then rpop pending_messages-#{ARGV[0]} and discard
	#  if not, then email or other notify, and probably exit with failure
end
