#!/usr/bin/env ruby

if $0 =~ /^(?:|.*\/)http_([^_]+)_/
  host = $1
end
abort "# Error: couldn't understand what I'm supposed to monitor." unless host

user = ENV['user'] || 'user'
password = ENV['password'] || 'user'

if (ARGV[0] == 'config')
  puts "host_name #{host}" unless host == 'localhost'

  puts "multigraph dsl_rate"
  puts "graph_title DSL line speed"
  puts "graph_args --base 1000 -l 0"
  puts "graph_vlabel bps"
  puts "graph_category network"
  puts "downstream.label downstream"
  puts "downstream.type GAUGE"
  puts "downstream.min 0"
  puts "downstream.cdef downstream,1000,*"
  puts "upstream.label upstream"
  puts "upstream.type GAUGE"
  puts "upstream.min 0"
  puts "upstream.cdef upstream,1000,*"

  puts "multigraph dsl_snr"
  puts "graph_title DSL SNR"
  puts "graph_args --base 1000 -l 0"
  puts "graph_vlabel dB"
  puts "graph_scale no"
  puts "graph_category network"
  puts "downstream.label downstream"
  puts "downstream.type GAUGE"
  puts "downstream.min 0"
  puts "upstream.label upstream"
  puts "upstream.type GAUGE"
  puts "upstream.min 0"

  exit 0
end

require 'net/http'

class TPAdslStats
  def initialize(host, user, password)
    Net::HTTP.start( host ) do |http|
      req = Net::HTTP::Get.new('/statsadsl.html')
      req.basic_auth user, password
      response = http.request(req)
      abort "# Error: #{response.code} received fetching stats" unless response.is_a?(Net::HTTPSuccess)
      @html = response.body
    end
  end

  def field_values(label)
    if @html =~ />#{label}.*?<td>([0-9.]+).*?([0-9.]+)/m
      [$1, $2]
    else
      ['U', 'U']
    end
  end
end

stats = TPAdslStats.new(host, user, password)

puts "multigraph dsl_rate"
rate = stats.field_values('Rate')
puts "downstream.value #{rate[0]}"
puts "upstream.value #{rate[1]}"

puts "multigraph dsl_snr"
snr = stats.field_values('SNR')
puts "downstream.value #{snr[0]}"
puts "upstream.value #{snr[1]}"
