#!/usr/bin/env python
#-*- coding: iso8859-15 -*-

# clean_distfiles  0.2
# Author: Rafael Antonio Porras Samaniego
# 	rafa (at) distrobit (dot) net
#
# Testing: Daniel Plaza


# Cargar los paquetes necesarios
try:
	import os,sys,bz2,getopt
	from bz2 import BZ2File
except:
	print "Error when loading the necessary packages. The script was unable to continue."

# Los colores
sys.path = ["/usr/lib/portage/pym"]+sys.path
try:
	import portage,output
except:
	print "Error when loading the necessary packages. The script was unable to continue."
			

# Constantes
DIR = "/var/db/pkg"
distfiles = "/usr/portage/distfiles"


# Localiza los ficheros a proteger		
def ficheros_programa (dir):
	total = []

	# Primero se buscan  todos los ebuilds instalados
	for categoria in os.listdir(dir):
		ruta_categoria = dir + "/" + categoria
		if os.path.isdir(ruta_categoria):
			for programa in os.listdir(ruta_categoria):
				ruta_programa = ruta_categoria + "/" + programa
				if os.path.isdir(ruta_programa) and os.path.isfile(ruta_programa + "/environment.bz2"):
					ebz2 = BZ2File (ruta_programa + "/environment.bz2",'r')
					temp = ebz2.readline()[2:]
					if temp[0] == "'":
						for i in temp[1:-2].split():
							total.append(i)
					else:
						total.append(temp[:-1])
	
	return total

# Muestra una lista por pantalla
def muestra(lista):
	lista.sort()
	for i in lista:
		print i
		
# Busca los ficheros que se van a borrar
def lista_borrar (protegidos, ruta):
	a_borrar = []
	for fichero in os.listdir(ruta):
		if fichero not in protegidos and not os.path.isdir(ruta + "/" + fichero):
			a_borrar.append(fichero)
	
	return a_borrar
		

# Borra los ficheros que no estén en la lista en la ruta indicada
def borrar (ruta,a_borrar):
	for i in a_borrar:
		try:
			os.remove (ruta + "/" + i)
		except:
			print "This file's deletion failed: " + i
			continue
		print "Deleted: " + i


# Comenzamos
opts, args = getopt.getopt(sys.argv[1:], "f")
borrado = False
for o, a in opts:
	if o == "-f":
		borrado = True
	

# Mensaje de bienvenida
print "\n\t" + output.green ("clean_distfiles 0.2")
print "\nFeedback and bug reports to: rafa (at) distrobit (dot) net"
print "\nThis script will find files in " + output.red(distfiles) + " which are not necessary for any installed ebuild. Use it at your own risk! Please, wait while the script locates the unnecessary files..."

# Localizamos los ficheros
total = ficheros_programa(DIR)

# Mostramos los ficheros a borrar
a_borrar = lista_borrar (total, distfiles)
if not a_borrar:
	print "\nThere are no files to remove."
	sys.exit(0)
	
print "\nThe next files will be deleted:\n"	
muestra(a_borrar)

# Informar de como borrar
if not borrado:
	print "\nIf you want to delete these files, you need to execute this script with the next parameter: " + output.red("-f") + "."
	sys.exit(0)

# Borrar los ficheros
print "\nNow, the directory " + output.red(distfiles) + " will be purged. The script will delete the unnecessary files listed previously."
res = raw_input(output.red("Would you like to continue? (yes / no) "))
if res == 'y' or res == 'Y' or res =='yes' or res == 'Yes':
	print "Deleting files:"
	borrar(distfiles,a_borrar)
else:
	print "No file was deleted."

