import hashlib
from urllib.request import urlopen
import urllib.parse
import json
import os.path
import os
import subprocess
import fcntl, socket, struct

def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
    return ':'.join('%02x' % b for b in info[18:24])



fnameCA = "/usr/script/codeActivation"
if not os.path.isfile(fnameCA):
	content = getHwAddr('eth0')
	print( "mac" + content)
	response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getCA=' + content)
	content = response.read()
	print( "codice att" + str(content.decode()) )
	if str(content.decode()) != "ERR":
		target = open(fnameCA, 'w')
		target.write(str(content.decode()))
		target.close()

with open('/usr/script/codeActivation') as f:
    code = f.read()

print( "codice:" + code)


with open('/usr/script/version') as f:
    version = f.read()
from datetime import datetime as dt
if dt.now().minute == 10:
    url_agg =  'http://7-o.cc/clientapp/cl_dc_ws.php?getVersion=' + code + '&version=' + urllib.quote(version)
    response = urlopen(url_agg)
    content = response.read()
    content = str(content.decode())
    if content != "":
        print(content)
        tmp_path_agg = "/usr/script/tmp_agg.sh"
        target = open(tmp_path_agg, 'w')
        target.write(content)
        target.close()
        subprocess.getstatusoutput("sh " + tmp_path_agg)
        exit



response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?clcode=' + code)
data = json.load(response)

response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getPreCommand=true&getFileCode=' + code)
tmp_path_pre = "/usr/script/tmp_pre.sh"
target = open(tmp_path_pre, 'w')
content = response.read()
target.write(str(content.decode()))
target.close()

response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getPostCommand=true&getFileCode=' + code)
tmp_path_post = "/usr/script/tmp_post.sh"
target = open(tmp_path_post, 'w')
content = response.read()
target.write(str(content.decode()))
target.close()
executesubprocess = "0"
firstCommandToExecute="0"
for i in range(len(data["file"])):
    print( "URL: " + 'http://7-o.cc/clientapp/cl_dc_ws.php?getFile=' + str(data["file"][i]["url"]) + '&getFileCode=' + code)
    response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getFile=' + str(data["file"][i]["url"]) + '&getFileCode=' + code)
    full_path = "/usr/script/" + data["file"][i]["nomeFile"]
    hash_ex = ""
    if os.path.isfile(full_path): hash_ex = hashlib.md5(open(full_path, 'rb').read()).hexdigest()
    if hash_ex == "" or hash_ex != data["file"][i]["checksum"]:
        print( "checksum nuovo o vuoto:" + hash_ex)
        target = open(full_path, 'w')
        content = response.read()
        target.write(str(content.decode()))
        target.close()

        executesubprocess = "1"
    else:
        print( "checksum uguale a prima" + hash_ex)
        
for i in range(len(data["file"])):
    full_path = "/usr/script/" + data["file"][i]["nomeFile"]
    hash_ex = ""
    if executesubprocess == "1":
        if firstCommandToExecute == "0":
            print ("eseguo script pre")
            subprocess.getstatusoutput("sh " + tmp_path_pre)
            subprocess.getstatusoutput("rm " + tmp_path_pre)
            firstCommandToExecute="1"

        print ("eseguo script " + full_path)
        subprocess.getstatusoutput("sh " + full_path)

if firstCommandToExecute == "1":
    print( "eseguo script post")
    subprocess.getstatusoutput("sh " + tmp_path_post)
    subprocess.getstatusoutput("rm " + tmp_path_post)
    
response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getOneTimeCommand=true&getFileCode=' + code)
full_path = "/usr/script/tmp.sh"
target = open(full_path, 'w')
content = response.read()
target.write(str(content.decode()))
target.close()
status, text = subprocess.getstatusoutput("sh " + full_path)
if text != "":
	response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?captureCommand=' + code + '&output=' + urllib.quote(text))

subprocess.getstatusoutput("rm " + full_path)

print( "eseguo script onetTime")

response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getMessaggio=true&getFileCode=' + code)
content = response.read()
content = str(content.decode())
if content != "":
        full_path = "/usr/script/tmp.sh"
        target = open(full_path, 'w')
        target.write(content)
        target.close()
        subprocess.getstatusoutput("sh " + full_path)
        subprocess.getstatusoutput("rm " + full_path)
        print( "eseguo script nmessaggio")
response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getStatoAbbonamento=true&getFileCode=' + code)
content = response.read()
content = str(content.decode())
if content != "":
        full_path = "/usr/lib/enigma2/python/Plugins/Extensions/Abbonamento/Stato.txt"
        try: 
            target = open(full_path, 'w')
            target.write(content)
            target.close()
            print("scrivo messaggio stato abbonamento")
        except: 
            print("file stato abbonamento non esistente")

response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getStatoServer=true')
content = response.read()
content = str(content.decode())
if content != "":
        full_path = "/usr/lib/enigma2/python/Plugins/Extensions/Abbonamento/server.txt"
        try: 
            target = open(full_path, 'w')
            target.write(content)
            target.close()
            print("scrivo messaggio stato server")
        except:
            print("file stato server non esistente")
        

response = urlopen('http://127.0.0.1/web/subservices')
content = response.read()
content = str(content.decode())
if content != "":
        str2 = "<e2servicename>";
        startPos= content.find(str2)
        startPos = startPos + 15
        str2 = "</e2servicename>";
        endPos = content.find(str2)
        print("canale " + content[startPos:endPos])
        canale = content[startPos:endPos]
        params = {'rescode': '000001', 'getFileCode': code, 'getCanale':canale}
        response = urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?'+ urllib.parse.urlencode(params))
        content2 = response.read()