#!/usr/bin/ruby
# frozen_string_literal: true

# This reads the queue of "changed addresses" from electrum webhooks in the
# form "<address>/<customer_id>" and turns those into <tx_hash>/<address> =>
# customer_id keys for the bin/process_pending_btc_transactions script to run
# through and process more fully
#
# Usage: bin/process_pending-btc_transactions '{
#        pidfile : Text,
#        electrum : env:ELECTRUM_CONFIG,
#        }'

require "dhall"

CONFIG =
	Dhall::Coder
	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
	.load(ARGV[0], transform_keys: :to_sym)

require "redis"
require_relative "../lib/electrum"
require_relative "../lib/pidfile"

REDIS = Redis.new
ELECTRUM = Electrum.new(**CONFIG[:electrum])

PIDFile.new(CONFIG[:pidfile]).lock do |pid|
	loop do
		key, value = REDIS.brpop("exciting_#{ELECTRUM.currency}_addrs", 600)

		# Rewrite the pidfile so monit can see we're still alive
		pid.refresh

		# brpop allows blocking on multiple keys, and key tells us which one
		# signalled but in this case we know which one, so just make sure it's
		# not nil which means the timeout fired
		next unless key

		address, customer_id = value.split("/", 2)

		txids =
			ELECTRUM
			.getaddresshistory(address)
			.map { |item| "#{item['tx_hash']}/#{address}" }

		next if txids.empty?

		REDIS.hset(
			"pending_#{ELECTRUM.currency}_transactions",
			*txids.flat_map { |txid| [txid, customer_id] }
		)
	end
end
