#coding:utf-8
'''
Created on Sep 3, 2014
@author: root
'''
import commands
import os

from PyQt4.QtCore import SIGNAL, QFile, QString, QIODevice, QTextStream
from PyQt4.QtGui import QGridLayout
from PyQt4.QtGui import QGroupBox
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QRadioButton
from PyQt4.QtGui import QWidget, QHBoxLayout, QVBoxLayout

from base.infohintdialog import InfoHintDialog
from base.storeinfoparser import StoreInfoParser
from setting.logrecord import LogRecord


class TerminalStyleSetting(QWidget):
       
    def __init__(self,parent = None):
        super(TerminalStyleSetting,self).__init__(parent)
       
        vareGroupBox = QGroupBox()
        vareGroupBox.setTitle(u"启动选项")
        self.desktopVare = QRadioButton(u"桌面虚拟化")
        self.terminalVare = QRadioButton(u"系统虚拟化 ")
       
        self.setButton = QPushButton(u"设置")
        self.setButton.setObjectName("settingDlgBtn")
        self.setButton.setFixedSize(75,27)
        self.setButton.setFlat(True)
        vLayout = QGridLayout()
        vLayout.setMargin(30)
        vLayout.addWidget(self.desktopVare,0,0,1,2)
        vLayout.addWidget(self.terminalVare,1,0,1,2)
        
        vLayout.addWidget(self.setButton,3,2,1,1)
        myVLayout = QHBoxLayout()
        myVLayout.addSpacing(70)
        myVLayout.addLayout(vLayout)
        
        vareGroupBox.setLayout(myVLayout)
        
        self.closeButton = QPushButton(u"关闭")
        self.closeButton.setObjectName("settingDlgBtn")
        self.closeButton.setFixedSize(75,27)
        self.closeButton.setFlat(True)
        closeButtonLayout = QHBoxLayout()
        closeButtonLayout.addStretch()
        closeButtonLayout.addWidget(self.closeButton)
        
        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.setMargin(100)
        self.mainLayout.addWidget(vareGroupBox)
        self.mainLayout.addSpacing(100)
        self.mainLayout.addLayout(closeButtonLayout)
        self.connect(self.closeButton, SIGNAL("clicked()"),self.closeTabWidget)
        LogRecord.instance().logger.info(u"初始化")
        
        self.initTerminalVM()
        
        self.connect(self.setButton, SIGNAL("clicked()"),self.slotSetTerminalType)
    def closeTabWidget(self):
        self.emit(SIGNAL("closetabwidget"))    
    def initTerminalVM(self):
        LogRecord.instance().logger.info(u"初始化")
        if self.isTerminal() == "desktopVM":
            self.desktopVare.setChecked(True)
        elif self.isTerminal() == "systemVM":
            self.terminalVare.setChecked(True)
        elif self.isTerminal() == "terminalVM":
            self.vareTerminal.setChecked(True)
        else:
            self.desktopVare.setChecked(True)
            StoreInfoParser.instance().setTerminalType("desktopVM")
    
        self.replaceFirstMenuName()
    def isTerminal(self):
        LogRecord.instance().logger.info(u"得到配置文件中终端类型")
        typeValue = StoreInfoParser.instance().getTerminalType()
        if typeValue == "desktopVM":
            return "desktopVM"
        elif typeValue == "terminalVM":
            return "terminalVM"
        elif typeValue == "systemVM":
            return "systemVM"
    
    def replaceFirstMenuName(self):
        os.system("command")

        LogRecord.instance().logger.info(u"修改系统的grub文件")
        grub_file = QFile("/mcos/dvclient/grub/grub/grub.conf")
        if not grub_file.open(QIODevice.ReadOnly):
            grub_file.close()
            return
        
        fs = QTextStream(grub_file)
        fileContent = fs.readAll()
        grub_file.close()
        if QString(fileContent).contains("MCOS cDesktop Client Start"):
            return
     
        cmd =  "sed -i \"s/CentOS (2.6.32-431.el6.x86_64)/MCOS cDesktop Client Start/g\" /mcos/dvclient/grub/grub/grub.conf";
     
        ok = os.system(cmd)
        if ok != 0:
            LogRecord.instance().logger.info(u"替换grub.cfg中的'CentOS (2.6.32-431.el6.i686)'失败")
     
    def slotSetTerminalType(self):
        LogRecord.instance().logger.info(u"点击设置按钮")
        mount = os.system("mount -o loop -L Root /mcos/dvclient/grub/")
        if mount != 0 :
            InfoHintDialog(u"挂载Root失败！").exec_()
            return
        os.system("sed -i '/hiddenmenu/d' /mcos/dvclient/grub/grub/grub.conf")
        if self.desktopVare.isChecked():
            if not self.setCDesktop():
                InfoHintDialog(u'设置桌面虚拟化失败').exec_()
            else:
                StoreInfoParser.instance().setTerminalType("desktopVM")
                InfoHintDialog(u'设置桌面虚拟化成功').exec_()
                self.emit(SIGNAL("desktopTerminal"))
        elif self.terminalVare.isChecked():
            if not self.setCSystem():
                InfoHintDialog(u'设置系统虚拟化失败').exec_()
            else:
                StoreInfoParser.instance().setTerminalType("systemVM")
                InfoHintDialog(u'设置系统虚拟化成功').exec_()
                self.emit(SIGNAL("systemTerminal"))
                

        os.system("umount /mcos/dvclient/grub/")   
    def setMenuDefaultValue(self, value):
        
        LogRecord.instance().logger.info(u"设置系统虚拟化类型")
        cmdlist = "cat /mcos/dvclient/grub/grub/grub.conf | awk '{ if($0 ~ \"default \") {print NR}}'"
        statusOutput = commands.getstatusoutput(cmdlist)
        if statusOutput[0] == 0:
            rowNum = statusOutput[1]
            defaultValueCmd = QString("sed -i '%1s/.*/default %2/g' /mcos/dvclient/grub/grub/grub.conf").arg(rowNum).arg(value)
            ok = os.system(str(defaultValueCmd))
            if ok != 0:
                LogRecord.instance().logger.info(u"执行命令‘sed -i '%1s/.*/default=%s/g' /mcos/dvclient/grub/grub/grub.conf’失败" % str(value))
                return False
        else:
            LogRecord.instance().logger.info(u"执行命令‘cat /mcos/dvclient/grub/grub/grub.conf | awk '{ if($0 ~ \"default=\") {print NR}}’失败")
            return False
        
        return True
          
    def setMenuTimeoutValue(self, value):
        #修改timeout值
        cmdlist = "cat /mcos/dvclient/grub/grub/grub.conf | awk '{ if($0 ~ \"timeout \") {print NR}}'"
        statusOutput = commands.getstatusoutput(cmdlist)
        if statusOutput[0] == 0:
            rowNum = statusOutput[1]
            defaultValueCmd = QString("sed -i '%1s/.*/timeout %2/g' /mcos/dvclient/grub/grub/grub.conf").arg(rowNum).arg(value)
            ok = os.system(str(defaultValueCmd))
            if ok != 0:
                LogRecord.instance().logger.info(u"执行命令‘sed -i '%1s/.*/timeout=%s/g' /mcos/dvclient/grub/grub/grub.conf’失败" % str(value))
                return False
        else:
            LogRecord.instance().logger.info(u"执行命令‘cat /mcos/dvclient/grub/grub/grub.conf | awk '{ if($0 ~ \"timeout=\") {print NR}}’失败")
            return False
        
        return True
          
    def setCDesktop(self):
        #修改默认值default
        LogRecord.instance().logger.info(u"设置桌面虚拟化")
        if not self.setMenuDefaultValue(0):
            return False
        
        if not self.setMenuTimeoutValue(0):
            return False
        
        return True
        

    def setCSystem(self):
        LogRecord.instance().logger.info(u"设置系统虚拟化")
        if not QFile.exists("/mcos/dvclient/grub/boot.krn"):
            os.system("cp /mcos/dvclient/cfg/boot.krn /mcos/dvclient/grub/")
        cmdlist = "cat /mcos/dvclient/grub/grub/grub.conf"
        statusOutput = commands.getstatusoutput(cmdlist)
        if statusOutput[0] == 0:
            content = statusOutput[1]
            if not QString(content).contains("MCOS cSystem Client Start"):
                insertContent = "title MCOS cSystem Client Start\\n\\t" + \
                        "root (hd0,2)\\n\\t" + \
                        "kernel /boot.krn\\n\\t" + \
                        "boot\\n"
                        

                addCmd = "sed -i '$a %s' /mcos/dvclient/grub/grub/grub.conf" % insertContent
                if os.system(addCmd) != 0:
                    LogRecord.instance().logger.info(u"执行命令‘sed -i '%sa %s' /mcos/dvclient/grub/grub/grub.conf失败")
                    return False
            
            if not self.setMenuDefaultValue(1):
                return False
        
            if not self.setMenuTimeoutValue(5):
                return False
            
            return True
    
        else:
            return False
        
    def setCTerminal(self):
        LogRecord.instance().logger.info(u"设置系统虚拟化")
        if not self.setMenuDefaultValue(0):
            return False
        if not self.setMenuTimeoutValue(0):
            return False
        return True
        

        
