#!/usr/bin/env ruby

require "net/http"
require "rexml/document"
require "cgi"
#require "uri"

@app_name = "getdvbtchannels"


def elenco_province(mode=0)
	h = Net::HTTP.new( "www.dgtvi.it", 80)
	response=h.get('/dgtvi/copertura.aspx?TRS_ID=1550000',"")
	stringa=response.body
	stringa.gsub!(/\n/,'')
	stringa.sub!(/.*?seleziona la provincia(.*?)<\/select>.*$/,'\1')
	
	if mode == 1 then
		stringa.gsub!(/<option value="([^"]+)">/,'\1'+" ")
	end

	stringa.gsub!(/<[^>]*>/,'')
	stringa.gsub!(/<\/[^>]*>/,'')
	stringa.gsub!(/\r/,"\n")
	stringa.gsub!(/\t/,'')
	stringa.gsub!(/\n*([^\n]*)\n*/,'\1'+"\n")
	stringa.gsub!(/([^\n]*)\n$/,'\1')
	stringa
end




def comuni_bycode(codice,mode)

	h = Net::HTTP.new( "www.dgtvi.it", 80)
	response=h.post('/dgtvi/copertura.aspx?TRS_ID=1550000'+"&PROVID=#{codice}","")
	stringa=response.body

	stringa.gsub!(/\n/,'')
	stringa.sub!(/.*?seleziona il comune(.*?)<\/select>.*$/,'\1')

	if mode == 1 then
		stringa.gsub!(/<option value="([^"]+)">/,'\1'+" ")
	end

	stringa.gsub!(/<[^>]*>/,'')
	stringa.gsub!(/<\/[^>]*>/,'')
	stringa.gsub!(/\r/,"\n")
	stringa.gsub!(/\t/,'')
	stringa.gsub!(/\n*([^\n]*)\n*/,'\1'+"\n")
	stringa.gsub!(/([^\n]*)\n$/,'\1')
	stringa
end


def elenco_comuni(provincia,mode=0)

	province=elenco_province(1)
	l=/(\d+) (.*#{provincia}.*)/i.match(province)
	return nil if l == nil
	comuni_bycode(l[1],mode)

end



def elenco_frequenze(provincia,comune)
	
	province=elenco_province(1)
	l=/(\d+) (.*#{provincia}.*)/i.match(province)
	return nil if l == nil
	prov_code=l[1]
	comuni=comuni_bycode(prov_code,1)
	l=/(\d+) (.*#{comune}.*)/i.match(comuni)
	return nil if l == nil
	com_code=l[1];

	h = Net::HTTP.new( "www.dgtvi.it", 80)

	response=h.get('/dgtvi/copertura.aspx?TRS_ID=1550000'+"&PROVID=#{prov_code}&CITYID=#{com_code}&CS=1","")
	stringa=response.body
	
	stringa.gsub!(/\n/,'')
	stringa.gsub!(/ [ \t\r]*/,' ')
	stringa.gsub!(/\r/,'')
	stringa.gsub!(/<span id="[^"]*band">([^<]*)<\/span>/,"\nBand="+'\1'+"\n")
	stringa.gsub!(/<span id="[^"]*digital_f">([^<]*)<\/span>/,"\nFreq="+'\1'+"\n")
	stringa.gsub!(/<[^>]*>/,'')
	stringa.gsub!(/<\/[^>]*>/,'')

	ris=""

	while (true)
		l=/Band=([^\n]*)\n/.match(stringa)
		break if l==nil	

		ris=ris+l[1]+"  "
		stringa=l.post_match
		l=/Freq=([^\n]*)\n/.match(stringa)
		break if l==nil	

		ris=ris+l[1]+"\n";
		stringa=l.post_match
	end

	stampa="# Generated by GetDVBTChannels Ruby script by Bruno Morelli 20060716\n"
	stampa=stampa+"#Provincia=#{provincia} Comune=#{comune}\n"
	stampa=stampa+"#T freq bw fec_hi fec_lo mod transmission-mode guard-interval hierarchy\n"
	ris.each {

		|linea| linea.sub!(/uhf/i,"8MHz")
			linea.sub!(/vhf/i,"7MHz")
			linea.sub!(",",'.')
		l=/([^ ]*) (.*)/.match(linea)
		k=(l[2].to_f*1000*1000).to_i
		stampa=stampa+"T #{k} "+"#{l[1]} 2/3 1/2 QAM64 8k 1/32 NONE\n"

	}
	stampa
end


i=0
prgname="getdvbtchannels"
while (i<ARGV.length)
	case ARGV[i]
		when "--version" , "-v"
			puts "#{prgname} version 0.0.1\n"
			puts "Copyright (C) 2005 Free Software Foundation, Inc.\nThis is free software.  You may redistribute copies of it under the terms of\nthe GNU General Public License <http://www.gnu.org/licenses/gpl.html>.\nThere is NO WARRANTY, to the extent permitted by law.\n\nWritten by Bruno Morelli."
			exit
		when "--help" , "-h"
#			puts "#{prgname} [--help] [[--import mplayer|xavtv file] ...] [--output|-o file]"
			puts "#{prgname} [--help|-h] [--version|-v] [--list-prov] [--list-com province]"
			puts "\n\t--help			print this help and exit"
			puts "\t-h"
			puts "\n\t--version		print version information and exit"
			puts "\t-v\n\n"
			puts "\t--list-prov		retrieve from the WWW and print all supported provinces, then exit"
			puts "\t--list-com province	retrieve from the WWW and print all supported municipality from"
			puts "\t			a given province, then exit\n\n"
			puts "\t--get-freq province municipality"
			puts "\t			print dvb-t frequencies for the given province-municipality and exit"

			puts "\nWritten by Bruno Morelli"
			exit 0;
		when "--list-prov"
			puts elenco_province
			exit 0;
		when "--list-com"
			i=i+1
			provincia=ARGV[i] if ARGV[i] != nil
			
			if provincia == nil  then
				puts "Error: manca il nome della provincia"
				exit
			end
			i=i+1
			puts elenco_comuni(provincia)
			exit
		when "--get-freq"
			i=i+1
			provincia=ARGV[i] if ARGV[i] != nil
			if provincia == nil  then
				puts "Error: manca il nome della provincia"
				exit
			end
			i=i+1
			comune=ARGV[i] if ARGV[i] != nil
			if comune == nil  then
				puts "Error: manca il nome del comune"
				exit
			end
			puts elenco_frequenze(provincia,comune)
			exit

		else
			puts "Error: \"#{ARGV[i]}\" unknown argument"
			exit
	end

end
