#!/usr/bin/env python3

#script de inicio, publica serial de rpi
import json
import requests
import os
import commands
import shutil
import ConfigParser
from time import sleep

config = ConfigParser.ConfigParser()
config.readfp(open(r'/boot/geko.txt'))

gekoserver = config.get('geko', 'IP_SERVIDOR')
gekobase = config.get('geko', 'BASE_DATOS')
iddispositivo = config.get('geko', 'ID_DISPOSITIVO')
idnet = config.get('geko', 'ETHERNET')

def download_file(url, base):
    local_filename = url.split('/')[-1]
    with requests.get(url, stream=True) as r:
        with open(base + local_filename, 'wb') as f:
            shutil.copyfileobj(r.raw, f)

    return local_filename

def getMAC(interface):
    try:
        str = open('/sys/class/net/' + interface + '/address').read()
    except:
        str = "00:00:00:00:00:00"
    return str[0:17]

def getrevision():
    revision = "0000"
    try:
        f = open('/proc/cpuinfo','r')
        for linea in f:
            if linea[0:8]=='Revision':
                longitud =len(linea)
                revision = linea[11:longitud-1]
        f.close()
    except IOError:
        revision = "0000"
    return revision

def getserial():
    cpuserial = "00000000"
    try:
        f = open('/proc/cpuinfo','r')
        for linea in f:
            if linea[0:6]=='Serial':
                cpuserial = linea[10:-1]
        f.close()
    except IOError:
        cpuserial = "ERROR000000000"
    return cpuserial


if __name__ == '__main__':
    urlservicio = "http://totem/pantalla/"
    serial = getserial()
    iprpy = commands.getoutput('hostname -I').rsplit(' ', 2)[0]
    #stats = psutil.disk_usage('/')
    query = {'Serial': serial, 'Resolucion': '100x100', 'Ip': iprpy, 'Mac': getMAC(idnet), 'IdPantalla': iddispositivo, 'Reinicio': 1}
    response = requests.post(urlservicio + "control_pantalla.php", json = query)
    respuesta = json.loads(response.text)
    sleep(5)

    while True:
        sleep(5)
        iprpy = commands.getoutput('hostname -I').rsplit(' ', 2)[0]
        #print iprpy
        query = {'Serial': serial, 'Resolucion': '100x100', 'Ip': iprpy, 'Mac': getMAC(idnet), 'IdPantalla': iddispositivo}
        response = requests.post(urlservicio + "control_pantalla.php", json = query)
        print(response.text)
        respuesta = json.loads(response.text)
        if respuesta["error_code"] == 0:
            if respuesta["EstadoPantalla"] == 2:
                print ('Debo reiniciar')
                os.system('sudo reboot')
            else:
                print ('No reiciar')
