#!/usr/bin/env ruby

INTERVAL = ENV['COLLECTD_INTERVAL'].to_i
HOSTNAME = ENV['COLLECTD_HOSTNAME']

def gather cmd
  counts = {}
  `#{cmd}`.lines.each do |l|
    dev = nil
    gw = nil
    if l =~ / dev (\S+)/
      dev = $1
    end
    if l =~ / via (\S+)/
      gw = $1
    end
    if gw and dev
      target = [gw, dev].join "%"
      counts[target] = 0 unless counts.has_key? target
      counts[target] += 1
    end
  end
  counts
end

loop do
  v4 = gather "ip -4 route"
  v4.each do |target,count|
    puts "PUTVAL \"#{HOSTNAME}/exec-routes4/routes-#{target}\" interval=#{INTERVAL} N:#{count}"
  end

  v6 = gather "ip -6 route"
  v6.each do |target,count|
    puts "PUTVAL \"#{HOSTNAME}/exec-routes6/routes-#{target}\" interval=#{INTERVAL} N:#{count}"
  end

  sleep INTERVAL
end
