#!/usr/bin/ruby

require 'net/telnet'
require 'cgi'
require 'mysql'
require 'iconv'

# <config>

# taken from: http://www.w3.org/International/questions/qa-forms-utf-8
UTF8REGEX = /\A(?:
                 [\x09\x0A\x0D\x20-\x7E]            # ASCII
               | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
               |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
               | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
               |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
               |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
               | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
               |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
               )*\z/mnx
# cf. Paul Battley
#   http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/
def validate_utf8(value)
  Iconv.iconv('UTF-8//IGNORE', 'UTF-8', (value + ' ') ).first[0..-2]
end

# Where to reach liquidsoap, and which operator should be queried for metadatas
liq_host = "localhost"
liq_port = 1234
liq_last = "history.get"

# Base URL to the icecast server, don't forget the trailing slash
ice_host = "http://localhost:8000/"

# </config>

puts "<info>"

# Liquidsoap uptime
conn = Net::Telnet::new("Host" => liq_host, "Port" => liq_port)
conn.puts("uptime")
conn.waitfor("Match" => /^END$/) do |data|
  puts "  <uptime>#{data.sub(/\nEND\n/,"")}</uptime>"
end

# Number of icecast listeners
ice = IO.popen("wget #{ice_host}status2.xsl -O - 2> /dev/null")
5.times do ice.readline end
match = /.*?,.*?,.*?,([0-9]+)/.match(ice.readline)
if match then
  puts "  <listeners>#{match[1]}</listeners>"
end

# Last ten tracks

conn.puts(liq_last)
conn.waitfor("Match" => /^END$/) do |data|
  data = data.sub(/END$/,"")
  data = data.sub(/^--- [0-9]+ ---\n/,"")
  data.split(/--- [0-9]+ ---\n/).reverse.each do |block|
    puts "  <block>"
    block.split(/\n/).each do |line|
      match = /([a-z_]+)="(([^\\]|\\.)*)"/.match(line)
      if match then
        key = match[1]
        value = match[2].gsub(/\\n/,"\n").gsub(/\\(.)/,"\\1").gsub(/ /,"")
        value = CGI.escapeHTML(value)
        # value = validate_utf8(value)
        # if value =~ UTF8REGEX then
          puts "    <item><key>#{key}</key><value>#{value}</value></item>"
          if key == "artist" then artist = value end
          if key == "title"  then title  = value end
        # end
      end
    end
    puts "  </block>"
  end
end

puts "</info>"
