#!/usr/bin/python
import sys,commands,math

global urlbase,wget,col
#urlbase="http://localhost/websites/popcon-ubuntu/popcon.ubuntu.com/"
urlbase="http://popcon.ubuntu.com/"
#urlbase="http://popcon.debian.org/"
urlbase="http://popcon.ubuntu.com/"
wget='wget -qNr -O '
col=int(commands.getoutput('export COLUMNS; echo $COLUMNS'))

def main():
	i=init()
	s=scarica(i[0],i[1],i[2],i[3],i[4],0)
	e=elabora(i[0],s[0],i[5])
	calcola(e[0],e[1],e[2],e[3])
	sys.exit(0)
	
def init():
	l=len(sys.argv) #parole in linea di comando
	if (l!=2):
		if (l==1):
			print "Inserire un nome di pacchetto\n es: $ sudo ./idp.py htop"
			sys.exit(1)
		elif (l>2):
			print "Attenzione: non accetto piu' di un pacchetto per volta! Solo il primo verra' considerato"
	p=sys.argv[1]
	print ""
	h=len(p)+2
	h=h*"="
	print h.center(col)
	print p.upper().center(col)
	print h.center(col)	
	gfile='by_vote.gz'
	sez=commands.getoutput('apt-cache show -q=2 '+p+' |grep -m 1 \"Section: \" |sed -e \'s/Section:\s//g\'')
	commands.getoutput('echo \"'+sez+'\" > tf~')
	r=commands.getoutput('wc -l tf~ |sed -e \'s/\stf~//g \'')
	r=int(r)
	if (r!=1):
		print "Errore: pacchetto inesistente o errore nel db locale,"
		print "prova ad aggiornare il db pacchetti con 'sudo apt-get update'"
		sys.exit(1)
	#se non esiste /usr/bin/wget: FIXME
		#print "Installa wget e riprova, grazie!"
		#sys.exit(1)
	if (sez.count('/')==0): #
		ramo='main'
		cat=sez
	else:
		sez=sez.rsplit('/') #
		ramo=sez[0]
		cat=sez[1]
	print "Ramo: "+ramo
	print "Categoria: "+cat.strip('/')
	return [gfile,urlbase,wget,ramo,cat,p]

def scarica(gfile,urlbase,wget,ramo,cat,unkn):
	catfile=ramo+'_'+cat.strip('/')+'_'+gfile
	if (unkn!=1):
		cat+='/'
		print "Recupero graduatoria globale   ("+urlbase+gfile+")..."
		commands.getoutput(wget+gfile+' '+urlbase+gfile) #scarica graduatoria globale ordinata per voto
		#se by_vote.gz esiste FIXME
		print "OK"
	print "Recupero graduatoria di categoria   ("+urlbase+ramo+"/"+cat+gfile+")..."
	commands.getoutput(wget+catfile+' '+urlbase+ramo+'/'+cat+gfile) #scarica graduatoria della categoria ordinata per voto
	#se catfile esiste FIXME
	print "OK"
	return [catfile]

def elabora(gfile,catfile,p):
	commands.getoutput('zcat '+catfile+' | grep -m 1 \"'+p+'   \" > tf~')
	test=commands.getoutput('cat tf~')
	if (test=='' or test.isspace()==1):
		print "Maledizione, il pacchetto e' in 'unknown', devo riscaricare la categoria!"
		unkn=1
		s=scarica(gfile,urlbase,wget,'unknown','',1)
		return elabora(gfile,s[0],p)
	c_rank=float(commands.getoutput('sed -e \'1!d\' tf~').rsplit(' ')[0]) #totale entry in graduatoria della categoria
	#print c_rank
	commands.getoutput('zcat '+catfile+' | grep \"Total   \" > tf~')
	c_tot=int(commands.getoutput('sed -e \'1!d\' tf~').rsplit(' ')[0]) #totale entry in graduatoria della categoria
	#print c_tot
	commands.getoutput('zcat '+gfile+' | grep \"Total   \" > tf~')
	g_tot=int(commands.getoutput('sed -e \'1!d\' tf~').rsplit(' ')[0]) #totale entry in graduatoria globale
	#print g_tot
	grep_tmp=commands.getoutput('zcat '+gfile+' | grep -m 1 \"'+p+'   \" > tf~')
	g_rank=float(commands.getoutput('sed -e \'1!d\' tf~').rsplit(' ')[0]) #rank in graduatoria globale
	#print g_rank
	commands.getoutput('rm -f *.gz tf~') #rimuovo file temporanei
	return [g_tot,g_rank,c_tot,c_rank]
	
def calcola(g_tot,g_rank,c_tot,c_rank):
	idp=(((g_tot - g_rank) / g_tot) + ((c_tot - c_rank) / c_tot)) * 50 #calcolo I.D.P.
	if (idp-round(int(idp),1) < 0.5): #arrotondamento all'intero
		idp=math.floor(idp) 
	else:
		idp=math.ceil(idp)
	print ""
	idp="I.D.P.="+str(int(idp))+"%"
	print idp.center(col)
	print ""
	
main()
