#/usr/bin/env python 
 
"""
Desinstalador de personalizado de postgresql por
el Ingeniero Victor Teran Herrera.
 
GPL(V3)
 
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
 
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>
"""
from os import remove, system, getcwd, mkdir
from time import sleep
from os.path import isdir, isfile, join
import subprocess
 
 
 
def makelogs(list_noexiste, list_obviados, list_eliminados):
    Dictionary={'not_found':list_noexiste, 'passed':list_obviados, 'deleted':list_eliminados}
    actions={'not_found':'que no existieron', 'passed':'obviados', 'deleted':'eliminados'}
    for x in Dictionary.keys():
        if isfile(join(getcwd(),'postgresql_delete_logs','log_'+x+'.txt'))==False:
           Log=open(join(getcwd(),'postgresql_delete_logs','log_'+x+'.txt'),'w')
           Log.write('Estos son los archivos $action en la ejecucion: \n'.replace("$action", actions[x]))
           for archivo in Dictionary[x]:
               Log.write(archivo + '\n')
           Log.close()
        else:
           Log=open(join(getcwd(),'postgresql_delete_logs','log_'+x+'.txt'),'a')
           for archivo in Dictionary[x]:
               Log.write(archivo + '\n')
           Log.close()
    return
 
def Deleteall(second_list_postgres_clean, firts_list_psql_clean):
    print "Removiendo paquetes obsoletos con aptitude clean"
    print "\n \n \n \n"
    system('aptitude clean')
    print "\n \n \n \n"
    print "Comienza la eliminacion... en tres segundos \n \n"
    sleep(1)
    print "Comienza la eliminacion... en dos segundos \n \n"    
    sleep(1)
    print "Comienza la eliminacion... en un segundo \n \n"
    sleep(1)
    nobviados=0
    neliminados=0
    nnoexiste=0
    list_eliminados=[]
    list_obviados=[]
    list_noexiste=[]
    for lista in (second_list_postgres_clean, firts_list_psql_clean):
        for element in lista:
            element=str(element)
            if isdir(element) or isfile(element):
                print "Eliminando elemento " + element
                if element[0:12]=='/home/victor' or element[0:19]=='/usr/lib/pymodules/':
                    print "Elemento obviado " + element
                    nobviados=nobviados+1
                    list_obviados.append(element)
                else:
                    sleep(1)
                    if isdir(element):
                        system('rm -rf ' +element)
                    elif isfile(element):    
                        remove(element)
                    print "Eliminado " + element
                    neliminados=neliminados+1
                    list_eliminados.append(element)
            else:
                print "El elemento no existe " + element
                nnoexiste=nnoexiste+1
                list_noexiste.append(element)
 
    if isdir('/home/victor/.psql_history'):
        print "Eliminacion forzada /home/victor/.psql_history"  
        remove('/home/victor/.psql_history')
        print "Eliminado"
 
    print "Todos los elementos fueron borrados"
    print "Actualizando catalogo, espere por favor, esto puede tomar algunos minutos"
    system('updatedb')
    print "Elementos inexistentes " +str(nnoexiste)      
    print "Elementos obviados " +str(nobviados)
    print "Elementos Eliminados "+str(neliminados)
    print "Puede revisar los logs en " + join(getcwd(),'postgresql_delete_logs')
    if isdir(join(getcwd(),'postgresql_delete_logs'))==False:
        mkdir('postgresql_delete_logs')
        makelogs(list_noexiste, list_obviados, list_eliminados)
    else:
        makelogs(list_noexiste, list_obviados, list_eliminados)        
    print "Actualizacion terminada, ejecucion terminada" 
 
print """ \n\n\n\n\n This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
    \n\n\n\n\n
    """
 
print "Buen dia, este es un script para eliminar una instalacion \
       \n corrupta de postgresql\n\n"
 
control=raw_input('Introduzca 1 para continuar, cualquier otra tecla para salir: ')
 
if control==" ":
    print "Saliendo"
 
control=int(control)
 
if control==1:
    print "\n\nComienza adquisicion de datos, esto puede tardar algunos segundos..."    
    elements_psql_tuple=subprocess.Popen("/usr/bin/env locate "+ 'psql', shell=True, \
                    stdout=subprocess.PIPE).communicate()
    string_to_clean=str(elements_psql_tuple)
 
    firts_list_psql_clean=string_to_clean.replace("[","").replace("'","").replace("]","").replace("(","").replace   (")","").split('\\n')
 
    elements_postres_tuple=subprocess.Popen("/usr/bin/env locate "+ 'postgres', shell=True, \
                    stdout=subprocess.PIPE).communicate()
 
    string_to_clean=str(elements_postres_tuple)
 
    second_list_postgres_clean=string_to_clean.replace("[","").replace("'","").replace("]","").replace("(","").replace(")","").split('\\n')
 
    elements=second_list_postgres_clean.extend(firts_list_psql_clean)
    
    Deleteall(second_list_postgres_clean, firts_list_psql_clean)
else:
    print "Saliendo"