#!/usr/bin/env ruby

require 'socket'

HOSTNAME = IO::readlines("/proc/sys/kernel/hostname").join.chomp
INTERVAL = 60

def read_stats
  sock = UNIXSocket.new("/run/haproxy/haproxy-stats.sock")
  sock.send "show stat\n", 0
  data = sock.read()
  sock.close

  cols = []
  results = []
  data.lines.each do |line|
    line.chomp!
    if line =~ /^#\s*(.+)$/
      cols = $1.split(/,/)
    else
      rec = {}
      cols.zip(line.split(/,/)).each do |col,val|
        rec[col] = val if val and not val.empty?
      end
      results << rec
    end
  end
  results
end

loop do
  read_stats.each do |rec|
    pxname = rec['pxname']
    svname = rec['svname']
    rec.each do |key,val|
      next if key == 'pxname' or key == 'svname' or not val =~ /^\d+$/

      puts "PUTVAL \"#{HOSTNAME}/haproxy_#{pxname}-#{svname}/current-#{key}\" interval=#{INTERVAL} N:#{val}"
    end
  end

  sleep INTERVAL
end
