#coding:utf-8
'''
Created on Sep 17, 2014

@author: root
'''


import commands
import os

from PyQt4.QtCore  import QFile, QTextStream, QFileInfo, QDir, QObject, QIODevice
from PyQt4.QtXml import QDomDocument, QDomNodeList, QDomNode

from base.storeinfoparser import StoreInfoParser
from common import commondata


class Upgrade(QObject):
    def __init__(self,parent=None):
        super(Upgrade,self).__init__(parent)
        updateDir = QFileInfo(commondata.UPGRADE_DIR)
        if (not updateDir.isDir()):
            os.system("mkdir -p " + commondata.UPGRADE_DIR)
    
    #获取当前升级模式
    def getUpgradeMode(self):
        
        mode = StoreInfoParser.instance().getUpdates()
        manual = "mamual_upgrade"
        autoup = "auto_upgrade"
        if(mode.find(manual)>-1):
            return "mamual"
        elif(mode.find(autoup)>-1):
            return "auto"
        return ""
    
    #设置升级模式
    def setUpgradeMode(self,upgrade_mode):
       
        s = upgrade_mode
        StoreInfoParser.instance().setUpdates(s)
        return True
    
    
    def gethosttype(self):
        cmd = "uname -i"
        statusOutput = commands.getstatusoutput(cmd)
        if statusOutput[0] == 0:#如果是0，则执行成功
            output = statusOutput[1]#第二个元素就是命令行执行后的输出
      
        else:
            output = ""
            
        strtmp = output
        if(strtmp.find("arm")>-1):
            file_dir = commondata.ARM_DIR
            return ["arm" , file_dir]
        elif(strtmp.find("i386")>-1 or strtmp.find("i486")>-1 or strtmp.find("i586")>-1 or strtmp.find("i686")>-1 or strtmp.find("x86")>-1):
            file_dir = commondata.X86_DIR
            return ["x86", file_dir]
        else:
            return [" " , file_dir]
    
    def getPacket(self,urlserver,packtype,source_path):
     
        if( packtype == "xml" ):
            dist_path = commondata.UPDATE_INDEX_SERVER
        elif( packtype == "zip" ):
            dist_path = commondata.UPDATE_PAK_SERVER
        elif( packtype == "md5" ):
            dist_path = commondata.UPDATE_MD5_TEXT
    
        if(not urlserver.isEmpty() and not urlserver.isNull()):
            wget="wget -O "
            ftp_=" ftp://"
            cmd=wget+dist_path+ftp_+urlserver+source_path
            if( 0 == os.system(str(cmd))):
                return True
            
        return False
    
    #比较版本新旧
    def compareXmlWithBefore(self):
        #原文件路径/mcos/dvclient/cfg/update_index.xml,新文件/mcos/dvclient/update/update_index.xml
        serTime=self.getXmlDate(commondata.UPDATE_INDEX_SERVER)
        lastTime =self.getXmlDate(commondata.UPDATE_INDEX_OLD)
    
        if(not serTime.isNull() and not serTime.isEmpty() and not lastTime.isEmpty() and not lastTime.isNull()):
            
            #比较时间，确定是否是最新版本
            if(0 >= cmp(serTime,lastTime)):
                return -1
            return 1
        return -2
    
    def getXmlDate(self,filename):
        if (not QFile.exists(filename)):
            return ""
        file = QFile(filename)
        if(not file.open(QIODevice.ReadOnly)):
            return ""
        else:
            dom = QDomDocument()
            if(not dom.setContent(file)):
                file.close()
                return ""
            else:
                root = QDomNodeList()
                root = dom.elementsByTagName("autoupdater");
                if(len(root)==1):
                    node_root = QDomNode()
                    node_root = root[0]
                    node_info = QDomNodeList()
                    node_info = node_root.childNodes()
                    for i in range(len(node_info)):
                    
                        node_version = QDomNode() 
                        node_version = node_info[0]
                  
                        if(node_version.toElement().tagName()=="updateinfo"):
                            status_c = len(node_version.toElement().childNodes())
                            
                            for m in range(status_c):
                                status_cn_s = QDomNode()
                                status_cn_s = node_version.toElement().childNodes()[m]
                                if(status_cn_s.toElement().tagName()=="updateDate"):
                                    return status_cn_s.toElement().text()
                               
        return ""
    
    def rmPacket(self,type):
        if( type == "rmxml" ):
            os.system("rm -rf " + commondata.UPDATE_INDEX_SERVER);
        elif(type == "rmzip"):
            os.system("rm -rf " + commondata.UPDATE_INDEX_SERVER + " " + commondata.UPDATE_PAK_SERVER);
        elif(type == "rmall"):
            os.system("rm -rf " + commondata.UPDATE_MD5_TEXT + " " + commondata.UPDATE_PAK_SERVER + " " + commondata.UPDATE_INDEX_SERVER);
        return
    
    def md5Check(self):
        #下载的ｍｄ5 /mcos/dvclient/update/md5.text
        if (not QFile.exists(commondata.UPDATE_MD5_TEXT)):
            return False
    
        file = QFile(commondata.UPDATE_MD5_TEXT)
        if(not file.open(QIODevice.ReadOnly)):
            return False
        else:
            fs = QTextStream(file)
            md5_server = fs.readAll()
            file.close()
            
            if(not md5_server.isNull()):
                cmd = "md5sum " + commondata.UPDATE_PAK_SERVER
                """
                FILE * fp
                char buffer[1024]
                QString str
                QByteArray cdm_temp= cmd.toLatin1()
                char* cdm_temp_=cdm_temp.data()
                fp = popen(cdm_temp_,"r")
                """
                statusOutput = []
                output = ""
                statusOutput = commands.getstatusoutput(cmd)
                if statusOutput[0] == 0:#如果是0，则执行成功
                    output = statusOutput[1]#第二个元素就是命令行执行后的输出
                    #return output
                else:
                    output = ""
                    
                words = output.split("/")
                sep = words[0]
                filename = words[len(words)-1]
                md5_there = sep + filename
                if md5_there == md5_server:
                    return True
                return False

    def replaceFile(self):
        os.system("mkdir " + commondata.TMEP_DIR)
        if(0!=os.system("unzip -d " + commondata.TMEP_DIR + " " + commondata.UPDATE_PAK_SERVER)):
            return False
        if(QDir(commondata.TMEP_DIR + "/sbin").exists()):
            os.system("cp -rf " + commondata.TMEP_DIR + "/sbin/* " + commondata.MASS_CLIENT_DIR + "/sbin")
            os.system("chmod +x " + commondata.MASS_CLIENT_DIR + "/sbin/*")
        if(QDir(commondata.TMEP_DIR + "/window").exists()):
            os.system("cp -rf " + commondata.TMEP_DIR + "/window/* " + commondata.MASS_CLIENT_DIR + "/window");
            os.system("chmod +x " + commondata.MASS_CLIENT_DIR + "/window/*")
        if(QDir(commondata.TMEP_DIR + "/share").exists()):
            os.system("cp -rf " + commondata.TMEP_DIR + "/share/* " + commondata.MASS_CLIENT_DIR + "/share")
            if(QDir(commondata.TMEP_DIR + "/share/window").exists()):
                os.system("cp -rf " + commondata.MASS_CLIENT_DIR + "/share/window /usr/share/")
        os.system("cp -rf " + commondata.UPDATE_INDEX_SERVER + " " + commondata.UPDATE_INDEX_OLD)
        os.system("rm -rf " + commondata.TMEP_DIR)
        return True
    