import hashlib
import urllib2
import urllib
import json
import os.path
import os
import commands
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', ifname[:15]))
    return ':'.join(['%02x' % ord(char) for char in info[18:24]])



fnameCA = "/usr/script/codeActivation"
if not os.path.isfile(fnameCA):
	content = getHwAddr('eth0')
	print "mac" + content
	response = urllib2.urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getCA=' + content)
	content = response.read()
	print "codice att" + content
	if content != "ERR":
			
		target = open(fnameCA, 'w')
		target.write(content)
		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 = urllib2.urlopen(url_agg)
    content = response.read()
    if content != "":
        print content
        tmp_path_agg = "/usr/script/tmp_agg.sh"
        target = open(tmp_path_agg, 'w')
        target.write(content)
        target.close()
        commands.getstatusoutput("sh " + tmp_path_agg)
        exit



response = urllib2.urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?clcode=' + code)
data = json.load(response)

response = urllib2.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(content)
target.close()

response = urllib2.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(content)
target.close()
executeCommands = "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 = urllib2.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(content)
        target.close()

        executeCommands = "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 executeCommands == "1":
        if firstCommandToExecute == "0":
            print "eseguo script pre"
            commands.getstatusoutput("sh " + tmp_path_pre)
            commands.getstatusoutput("rm " + tmp_path_pre)
            firstCommandToExecute="1"

        print "eseguo script " + full_path
        commands.getstatusoutput("sh " + full_path)

if firstCommandToExecute == "1":
    print "eseguo script post"
    commands.getstatusoutput("sh " + tmp_path_post)
    commands.getstatusoutput("rm " + tmp_path_post)
    
response = urllib2.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(content)
target.close()
status, text = commands.getstatusoutput("sh " + full_path)
if text != "":
	response = urllib2.urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?captureCommand=' + code + '&output=' + urllib.quote(text))

commands.getstatusoutput("rm " + full_path)

print "eseguo script onetTime"



response = urllib2.urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getMessaggio=true&getFileCode=' + code)
if response != "":
        full_path = "/usr/script/tmp.sh"
        target = open(full_path, 'w')
        content = response.read()
        target.write(content)
        target.close()
        commands.getstatusoutput("sh " + full_path)
        commands.getstatusoutput("rm " + full_path)
        print "eseguo script nmessaggio"
response = urllib2.urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getStatoAbbonamento=true&getFileCode=' + code)
if response != "":
        full_path = "/usr/lib/enigma2/python/Plugins/Extensions/Abbonamento/Stato.txt"
        target = open(full_path, 'w')
        content = response.read()
        target.write(content)
        target.close()
        print "scrivo messaggio stato abbonamento"

response = urllib2.urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?getStatoServer=true')
if response != "":
        full_path = "/usr/lib/enigma2/python/Plugins/Extensions/Abbonamento/server.txt"
        target = open(full_path, 'w')
        content = response.read()
        target.write(content)
        target.close()
        print "scrivo messaggio stato server"

response = urllib2.urlopen('http://127.0.0.1/web/subservices')
if  response != "":
        content = response.read()
        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 = urllib2.urlopen('http://7-o.cc/clientapp/cl_dc_ws.php?'+ urllib.urlencode(params))
        content2 = response.read()