#!/usr/bin/python3
import subprocess
import sys

class Datalogger:
    def __init__(self, args=''):
        self.dataloggers={
        'ECOM EYE3': ['http://tunel.mine-360.com/datalogger_ecom_eye3.sh',1,],
        'ECOM EYE3 MASTER' : ['http://tunel.mine-360.com/datalogger_ecom_eye3_master.sh',1],
        'ECOM MINING' : ['http://tunel.mine-360.com/datalogger_ecom.sh',1],
        'GIMP EYE3': ['http://tunel.mine-360.com/datalogger_gimp_eye3.sh',1],
        'GIMP MINING' : ['http://tunel.mine-360.com/datalogger_gimp.sh',1],
        'MMR EYE3' : ['http://tunel.mine-360.com/datalogger_mmr_eye3.sh',1],
        'MMR MINING' : ['http://tunel.mine-360.com/datalogger_mmr.sh',1],
        'CABINA' : ['http://tunel.mine-360.com/datalogger_cabina.sh',1]}

        self.app(args)
        

    def comando(self,orden):
        orden_s=orden.split(' ')
        res=subprocess.check_output(orden_s)
        if res.decode()!='\n' or res.decode()!='':
            print(res.decode())

    def reemplazar(self,ruta_archivo, texto_out, texto_in):
        with open(ruta_archivo,'r') as archivo:
            contenido=archivo.read()
        contenido_2 = contenido.replace(texto_out,texto_in)

        with open(ruta_archivo, 'w') as archivo_nuevo:
            archivo_nuevo.write(contenido_2)

    def tipo(self):
        global nombre
        res=subprocess.check_output('machinename')
        nombre=res.decode().split('-')
        return nombre[0].lower() # return en minuscula

    def ver_datalogger(self, opcion):
        lista=[]
        resp=subprocess.check_output(['ls','/srv/']).decode()
        if self.tipo()=='mmr' and 'pruebas-riego' in resp:
            lista.append('MMR EYE3')
        if 'datalogger_mmr' in resp:
            lista.append('MMR MINING')
        if self.tipo()=='ecom' and 'dio' in resp:
            res2 = subprocess.check_output(['ls','/srv/dio/']).decode()
            if 'gps_config.json' in res2:
                lista.append('ECOM EYE3 MASTER')
            else:
                lista.append('ECOM EYE3')
        if 'datalogger_ecom' in resp:
            lista.append('ECOM MINING')
        if self.tipo()=='gimp' and 'dio' in resp:
            lista.append('GIMP EYE3')
        if 'datalogger_gimp' in resp:
            lista.append('GIMP MINING')
        for i in resp.split('\n'):
            if i=='datalogger':
                lista.append('CABINA')
        if len(lista)==0: print('No hay dataloggers instalados')
        #if opcion==1:
        for i in range(len(lista)):
            print(str(i+1)+'. '+lista[i])
        print('')
        if opcion==1:
            return []
        elif opcion==2:
            return lista
        
    def instalar_datalogger(self):
        self.comando('clear')
        print('SELECCIONE DATALOGGER A INSTALAR:\n')
        indice = 1
        lista = list(self.dataloggers.keys())
        for data in lista:
            if self.dataloggers[data][1]==1:
                print(str(indice)+'. '+data)
            else:
                print(str(indice)+'. '+data + ': No Disponible')
            indice=indice+1
        sel = input('Ingrese opcion o Q(q) para salir: ')
        if sel!='Q' and sel!='q':
            self.comando('wget -O /'+ self.dataloggers[lista[int(sel)-1]][0].split('/')[-1] +' '+ self.dataloggers[lista[int(sel)-1]][0])
            self.comando('sh /'+self.dataloggers[lista[int(sel)-1]][0].split('/')[-1])
            self.comando('rm /'+self.dataloggers[lista[int(sel)-1]][0].split('/')[-1])

    def desinstalar_datalogger(self):
        self.comando('clear')
        lista = self.ver_datalogger(2)
        if len(lista)==0: return
        sel = input('\nSeleccione Datalogger a desinstalar o (Q) para salir: ')
        if sel=='q' or sel=='Q' or len(lista)==0: 
            print('')
            return
        if lista[int(sel)-1]=='ECOM EYE3' or lista[int(sel)-1]=='ECOM EYE3 MASTER':
            self.desinstalar_ecom_eye3()
        elif lista[int(sel)-1]=='ECOM MINING':
            self.desinstalar_ecom()
        elif lista[int(sel)-1]=='GIMP EYE3':
            self.desinstalar_gimp_eye3()
        elif lista[int(sel)-1]=='GIMP MINING':
            self.desinstalar_gimp()
        elif lista[int(sel)-1]=='MMR EYE3':
            self.desinstalar_mmr_eye3()
        elif lista[int(sel)-1]=='MMR MINING':
            self.desinstalar_mmr()
        elif lista[int(sel)-1]=='CABINA':
            self.desinstalar_cabina()

    def desinstalar_ecom_eye3(self):
        print('Desinstalando datalogger ECOM')
        try:
            self.reemplazar('/srv/dio/desinstalar_datalogger.sh', 'sh /srv/dio/socketio-server-js/uninstall.sh','cd /srv/dio; sh /srv/dio/socketio-server-js/uninstall.sh')
            self.comando('sh /srv/dio/desinstalar_datalogger.sh')
            try:
                self.comando('rm -r /srv/dio')
            except: pass
            try:
                self.comando('rm -r /srv/mysqltools-caex')
                self.comando('rm -r /srv/mysqltools-caex.tar.gz')
            except: pass
            print('Datalogger completamente desinstalado')
        except:
            print('No se pudo desinstalar, pedir soporte')
    
    def desinstalar_gimp_eye3(self):
        print('Desisntalando Datalogger GIMP')
        try:
            try:
                self.reemplazar('/srv/dio/desinstalar_datalogger.sh', 'sh /srv/dio/socketio-server-js/uninstall.sh','cd /srv/dio; sh /srv/dio/socketio-server-js/uninstall.sh')
                self.reemplazar('/srv/dio/uninstall.sh','ecom-nrf24','esp32-sds mf-autoupload')
            except: pass
            try:
                self.comando('sh /srv/dio/desinstalar_datalogger.sh')
            except:
                self.comando('wget -O /desinstalar_gimp.sh http://tunel.mine-360.com/desisntalar_gimp')
                self.comando('sh /desinstalar_gimp.sh')
                self.comando('rm /desinstalar_gimp.sh')
            try:
                self.comando('rm -r /srv/dio')
            except: pass
            try:
                self.comando('rm -r /srv/mysqltools-caex')
                self.comando('rm /srv/mysqltools-caex.tar.gz')
            except: pass
            print('Datalogger completamente desinstalado')
        except:
            print('No se pudo desinstalar, pedir soporte')

    def desinstalar_mmr_eye3(self):
        print('Desinstalar datalogger MMR')
        try:
            try:
                self.comando('sh /srv/pruebas-riego/instalables/desinstalar_datalogger')
            except: 
                self.comando('wget -O /desinstalar_mmr.sh http://tunel.mine-360.com/desisntalar_mmr')
                self.comando('sh /desinstalar_mmr.sh')
                self.comando('rm /desinstalar_mmr.sh')
            try:
                self.comando('rm -r /srv/pruebas-riego')
            except: pass
            self.comando('rm -r /srv/mysqltools-regador')
            self.comando('rm -r /srv/mmr2-configure')
            self.comando('sudo systemctl stop autoupload')
            self.comando('sudo systemctl disable autoupload')
            self.comando('sudo systemctl daemon-reload')
            self.comando('sudo systemctl systemctl reset-failed')
            print('Datalogger completamente desinstalado')
        except:
            print('No se pudo desinstalar, pedir soporte')

    def desinstalar_cabina(self):
        self.comando('systemctl stop dio-apiRead')
        self.comando('systemctl disable dio-apiRead')
        self.comando('rm -f /etc/systemd/system/dio-apiRead.service')
        self.comando('systemctl daemon-reload')
        self.comando('systemctl stop apiAutoupload')
        self.comando('systemctl disable apiAutoupload')
        self.comando('rm /etc/systemd/system/apiAutoupload.service')
        self.comando('rm -r /srv/datalogger')
        self.comando('systemctl daemon-reload')
        self.comando('rm /bin/cabina')

    def desinstalar_gimp(self):
        self.comando('sh /srv/datalogger_gimp/uninstall.sh')
        self.comando('rm -r /srv/datalogger_gimp')
        print('Datalogger Desinstalado')

    def desinstalar_ecom(self):
        self.comando('sh /srv/datalogger_ecom/uninstall.sh')
        self.comando('rm -r /srv/datalogger_ecom')
        print('Datalogger Desinstalado')

    def desinstalar_mmr(self):
        self.comando('sh /srv/datalogger_mmr/uninstall.sh')
        self.comando('rm -r /srv/datalogger_mmr')
        print('Datalogger Desinstalado')

    def app(self, args):
        if args == '-v':
            self.ver_datalogger(1)
        else:
            self.comando('clear')
            print('Sistema de Gestion de Datalogger\n')
            while True:
                sel=input('Seleccione Tarea a realizar:\n \n1. Ver Datalogger Instalados\n2. Instalar Datalogger\n3. Desinstalar Datalogger\n4. Salir\n\nIngrese opcion: ')
                if sel=='1':
                    self.ver_datalogger(1)
                elif sel=='2':
                    self.instalar_datalogger()
                elif sel=='3':
                    self.desinstalar_datalogger()
                else: break

####LISTA DE ARGUMENTOS
# -v Ver Dataloggers Instalados
try:
    args = sys.argv[1]
    datalogger = Datalogger(args)
except:
    datalogger = Datalogger()

