require 'net/http'

Net::HTTP.version_1_2

class DashPlugin < Plugin
  def initialize
    super
    @t_handle = nil
    @freq = nil
    @tell = nil
  end
  def help(plugin, topic="")
    "dash => check dWeb dashboard status, dash every <period> => check dashboard every <period> seconds, report if problems found, dash stop => stop timed checks, dash status => display current timed monitoring setup"
  end
  def cleanup
    if(@t_handle)
      @bot.timer.remove(@t_handle)
    end
  end
  def getdash
    query = "/auth.cgi"
    ontimer = false
    proxy_host = nil
    proxy_port = nil

    http = Net::HTTP.new("uk.dash.dweb.intranet.db.com", 80, proxy_host, proxy_port)

    req = Net::HTTP::Get.new(query)
    req.basic_auth "dweb", "tigtpli1999"
    http.start {|http|
      resp = http.request(req)
      if resp.code == "200"
        due = false
        result = resp.body
        # cheeeeeeeeeze
        if(result.length > 0)
          hosts = Hash.new
          result.each_line {|l|
            if (l =~ /"link5">(.*)<\/a><\/b><\/font><br><\/td><td align=right><img src="\/images\/(.*)\.gif" align=right><\/td>/)
              puts $1, $2
              hosts[$1] = $2 unless($2 == "green")
            end
          }
          if(hosts.length > 0)
            response = ""
            hosts.sort.each {|a|
              host = a[0]
              col = a[1]
              response += ", " if(response.length > 0)
              response += "#{host} is #{col}"
            }
            return "wuh-oh, #{response}"
          else
            return false
          end
        end
      else
        return "got reponse code #{resp.code} :("
      end
    }
    return false
  end
  def privmsg(m)

    if(m.params =~ /^every (\d+)$/)
      period = $1.to_i
      if(@t_handle)
        @bot.timer.remove(@t_handle)
      end
      @t_handle = @bot.timer.add(period) {
        res = getdash
        if(res && res =~ /red/)
          @bot.say m.replyto, res
        end
      }
      @tell = m.replyto
      @freq = period
      @bot.okay m.replyto
      return
    elsif(m.params =~ /^stop$/)
      if(@t_handle)
        @bot.timer.remove(@t_handle)
      end
      @tell = nil
      @freq = nil
      @bot.okay m.replyto
      return
    elsif(m.params =~ /^status$/)
      if(@tell)
        m.reply "currently checking the dashboard every #{@freq}, telling #{@tell}"
      else
        m.reply "not currently monitoring the dashboard"
      end
      return
    end

    res = getdash
    unless(res)
      m.reply "everything's green :)"
    else
      m.reply res
    end
  end
end
plugin = DashPlugin.new
plugin.register("dash")
