#!/usr/bin/ruby.ruby3.3
# frozen_string_literal: true

Process.setproctitle("discourse prometheus-collector")

require 'oj'
require 'prometheus_exporter'
require 'prometheus_exporter/server'
require 'rbtrace' if ENV['RBTRACE'] == "1"

module DiscoursePrometheus; end

require_relative '../lib/internal_metric/base'
require_relative '../lib/internal_metric/global'
require_relative '../lib/internal_metric/job'
require_relative '../lib/internal_metric/process'
require_relative '../lib/internal_metric/web'
require_relative '../lib/internal_metric/custom'
require_relative '../lib/collector'

$port = ARGV[0].to_i
bind = ARGV[1]
$parent_pid = ARGV[2].to_i
$pid_file = ARGV[3]

STDERR.puts "#{Time.now}: Starting Prometheus Collector pid: #{Process.pid} port: #{$port}"

if $parent_pid > 0
  STDERR.puts "#{Time.now}: Prometheus Collector is monitoring #{$parent_pid}"
  Thread.new do
    def alive?(pid)
      Process.kill(0, pid)
      File.read($pid_file).to_i == Process.pid
    rescue
      false
    end

    while true
      begin
        unless alive?($parent_pid)
          STDERR.puts "Parent was terminated!"
          Process.kill "TERM", Process.pid
          sleep 10
          Process.kill "KILL", Process.pid
        end
      rescue => e
        STDERR.puts "URGENT monitoring thread had an exception #{e}"
      end
      sleep 5
    end
  end
end

PrometheusExporter::Metric::Base.default_prefix = 'discourse_'

collector = DiscoursePrometheus::Collector.new
server = PrometheusExporter::Server::WebServer.new port: $port, bind: bind, collector: collector

server.start

sleep
