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

from PyQt4.QtCore import Qt, SIGNAL, QLatin1String, QString, QRect, QPoint
from PyQt4.QtGui import QLabel, QLineEdit, QKeySequence, QAction, QKeyEvent, QPushButton, QGridLayout, QHBoxLayout, QPainter, QLinearGradient, QBrush, QPen, QColor, \
                        QVBoxLayout, QDialog

from base.infohintdialog import InfoHintDialog


class ChanPw(QDialog):
    def __init__(self,parent=None):
        super(ChanPw,self).__init__(parent)
        self.setWindowTitle(u"修改密码")
        self.setWindowFlags(Qt.FramelessWindowHint|Qt.Dialog)

        self.setFixedSize(400,250)
        self.setStyleSheet("QWidget{font-size : 15px;}"
                           "QLineEdit{border:1px groove rgb(170,214,252);}"
                           "QLineEdit{height:25;}"
                           "QComboBox{border: 1px groove rgb(170,214,252);}"
                           "QComboBox{height:25;}"
                           "QComboBox::drop-down{border-bottom-right-radius: 3px;}"
                           "QComboBox::drop-down{subcontrol-origin: padding;}"
                           "QComboBox::drop-down{subcontrol-position: top right;}"
                           "QComboBox::drop-down{width: 20px;}"
                           "QComboBox::drop-down{border-left-width: 1px;}"
                           "QComboBox::drop-down{border-left-color: rgb(170,214,252);}"
                           "QComboBox::drop-down{border-left-style: solid;}"
                           "QComboBox::drop-down{border-top-right-radius: 3px;}"
                           "QComboBox::down-arrow {image:url(../images/s2_r8_c10.gif);}"
                           "QPushButton{background:url(../images/button.png);font-size: 12pt;}"
                           )
        self.title = u"修改管理员密码"
        self.labelOld = QLabel(u"原密码:")
        self.labelNew = QLabel(u"新密码:")
        self.labelNewt = QLabel(u"确认密码:")
        
        self.lineEditOldPw = QLineEdit()
        self.lineEditOldPw.setEchoMode(QLineEdit.Password)
        self.lineEditNewPw = QLineEdit()
        self.lineEditNewPw.setEchoMode(QLineEdit.Password)
        self.lineEditNewPwt = QLineEdit()
        self.lineEditNewPwt.setEchoMode(QLineEdit.Password)
        
        
        self.cancelButton = QPushButton(u"取消")
        self.cancelButton.setFixedSize(79,31)
        self.cancelButton.setFlat(True)
        self.okButton = QPushButton(u"确定")
        self.okButton.setFixedSize(79,31)
        self.okButton.setFlat(True)
        
        self.connect(self.okButton,SIGNAL("clicked()"),self.on_pushButtonChPw_clicked)
        self.connect(self.cancelButton,SIGNAL("clicked()"),self.on_pushButtonCancel_clicked)
        
        hLayout = QHBoxLayout()
        hLayout.addStretch()
        hLayout.addWidget(self.okButton)
        hLayout.addStretch()
        hLayout.addWidget(self.cancelButton)
        hLayout.addStretch()
        
        self.mainLayout = QGridLayout()
        self.mainLayout.setMargin(0)
        self.mainLayout.addWidget(self.labelOld,0,0)
        self.mainLayout.addWidget(self.lineEditOldPw,0,1)
        self.mainLayout.addWidget(self.labelNew,1,0)
        self.mainLayout.addWidget(self.lineEditNewPw,1,1)
        self.mainLayout.addWidget(self.labelNewt,2,0)
        self.mainLayout.addWidget(self.lineEditNewPwt,2,1)
        
        mhLayout = QHBoxLayout()
        mhLayout.addSpacing(50)
        mhLayout.addLayout(self.mainLayout)
        mhLayout.addSpacing(50)
        
        mLayout = QVBoxLayout()
        mLayout.addSpacing(70)
        mLayout.addLayout(mhLayout)
        mLayout.addSpacing(30)
        mLayout.addLayout(hLayout)
        self.setLayout(mLayout)
        
        self.actionA = QAction(self)
        self.actionB = QAction(self)
        self.actionA.setShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_W))
        self.actionB.setShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_C))
        self.addAction(self.actionA)
        self.addAction(self.actionB)
        self.connect(self.actionA,SIGNAL("triggered()"),self.slotColorEggs)
        self.connect(self.actionB,SIGNAL("triggered()"),self.on_pushButtonCancel_clicked)

    def slotColorEggs(self):
        InfoHintDialog(u"yyyyyyyyyy").exec_()
        
    def getSystemAdministratorPassword(self):
        #执行命令，收集结果
        output = None
        statusOutput = commands.getstatusoutput("cat /etc/shadow | grep root:")
        if statusOutput[0] == 0:
            output = statusOutput[1]
        if not output:
            InfoHintDialog(u'读取系统密码异常').exec_()
            return None
        crylist = output.split(":")
        if len(crylist) < 2:
            InfoHintDialog(u'读取系统密码异常').exec_()
            return None
        return crylist[1]
    def cleanInfo(self):
        self.lineEditOldPw.clear()
        self.lineEditNewPw.clear()
        self.lineEditNewPwt.clear()
    
    def checkPasswd(self, passwd,crypasswd):
        temp = crypasswd.split("$");
        count = len(temp)
        if 4 != count:
            return False
        alg = temp[1]
        salt= temp[2]
        passwdchar = passwd.toLatin1().data()
        randomchar = "$"+alg+"$"+salt+"$"
        usercry = crypt.crypt(passwdchar,randomchar)
        crystr= QString(QLatin1String(usercry))
        #加密后的密文与系统存储的ｒｏｏｔ密码密文想比较
        if crypasswd == crystr:
            return True
        return False
    
    def on_pushButtonCancel_clicked(self):
        self.close()

    def on_pushButtonChPw_clicked(self):
        oldPw = self.lineEditOldPw.text()
        newPw = self.lineEditNewPw.text()
        newPwt = self.lineEditNewPwt.text()
        os.system("umount /etc/shadow")
        os.system("cp -f /config/etc/shadow /etc/shadow")
        
        if( oldPw == "" or newPw == "" or newPwt == ""):
            #QMessageBox.information(self,u"信息",u"任意一项不得为空")
            InfoHintDialog(u"任意一项不得为空").exec_()
            return
        
            #验证原密码是否正确
            #读取/etc/shadow文件，获取以ｒｏｏｔ开头的行
        crypasswd = self.getSystemAdministratorPassword()
        if not crypasswd:
            InfoHintDialog(u'shadow文件中未存储root密码，无法完成验证').exec_()
            return
        if not self.checkPasswd(oldPw,crypasswd):
            InfoHintDialog(u'原密码错误，请确认后重新输入').exec_()
            self.emit(SIGNAL("passwordwrong"))
            return
        
        elif( newPw != newPwt):
            #QMessageBox.information(self,u"信息",u"两次输入的密码不一致")
            InfoHintDialog(u"两次输入的密码不一致").exec_()
            return
        
        if not self.checkPasswd(oldPw,crypasswd):
           
            InfoHintDialog(u'原密码错误，请确认后重新输入').exec_()
            self.emit(SIGNAL("passwordwrong"))
            return
        else:
            self.emit(SIGNAL("passwordright"))
           
            #原密码正确，修改ｒｏｏｔ密码
            if( self.changePasswd(newPw,crypasswd)):
                #QMessageBox.information(self,u"信息",u"修改密码成功")
                os.system("cp -f /etc/shadow /config/etc/shadow")
                os.system("mount --bind /config/etc/shadow /etc/shadow")
                
                InfoHintDialog(u'修改密码成功').exec_()
                self.close()
            else:
                #QMessageBox.information(self,u"错误",u"修改密码失败")
                InfoHintDialog(u'修改密码失败').exec_()
            return
    def changePasswd(self,newpd,oldcry):
        crypasswd = self.encryptionPasswd(newpd)
        
        newstr = "root:" + crypasswd
        oldstr = "root:" + QString(oldcry)
        #QString类型
        newstr.replace("/", "\/")
        newstr.replace("$", "\$")
        oldstr.replace("/", "\/")
        oldstr.replace("$", "\$")
        print (oldstr)
        print (newstr)
      
        
        cmd = "sed -i 's/" + oldstr + "/" + newstr + "/g' /etc/shadow"
        res = os.system(str(cmd))
        if(0 == res):
            return True
        return False
    def encryptionPasswd(self,passwd):#返回root密码
        crypasswd = self.getSystemAdministratorPassword()
        temp = crypasswd.split("$")
        alg = temp[1]
        salt= temp[2]
        #调用ｃｒｙｐｔ前，先将参数转化为char*
        ba = passwd.toLatin1()
        passwdchar = ba.data()
        random = "$"+alg+"$"+salt+"$"
        ba3 = QString(random).toLatin1()
        randomchar = ba3.data()
        usercry = crypt.crypt(passwdchar,randomchar)
        crystr= QString(QLatin1String(usercry))
        return crystr
    def mouseMoveEvent(self,event):
        if self.mousePressed:
            self.move(self.pos() + event.pos() - self.currentPos)   
        self.default = QString()
    def mousePressEvent(self,event):
        if event.buttons() == Qt.LeftButton:
            self.currentPos = event.pos()
            self.mousePressed = True
    def mouseReleaseEvent(self,event):
        if event.buttons() == Qt.LeftButton:
            self.mousePressed = False
    def paintEvent(self,event):
        titleHeight = 40
        bottomHeight = 50
        
        #画标题背景
        painter = QPainter(self)
        painter.save()
        linearGradient = QLinearGradient(0, 0,0,titleHeight)
        linearGradient.setColorAt(0, QColor(60,150,255))
        linearGradient.setColorAt(0.1, QColor(6,88,200))
        linearGradient.setColorAt(1, QColor(80,150,255))
        painter.setBrush(QBrush(linearGradient))
        contenRect = QRect(0, 0, self.width(), titleHeight)
        painter.fillRect(contenRect, QBrush(linearGradient))
        painter.restore()
        
        #画标题内容
        painter.save()
        painter.setPen(QPen(QColor(255, 255, 255),1))
        font = painter.font()
        font.setPointSize(12)
        painter.setFont(font)
        painter.drawText(QPoint(10,25), self.title)
        painter.restore()
        
        #画中间白色背景
        painter.save()
        painter.setPen(QPen(QColor(255, 255, 255),1))
        brush = QBrush(QColor(242,242,242))
        painter.setBrush(brush)
        contenRect = QRect(0, titleHeight, self.width()-1, self.height() - titleHeight - bottomHeight)

        painter.drawRect(contenRect)
        painter.restore()
        
        #画底层背景
        painter.save()
        brush = QBrush(QColor(219,234,255))
        painter.setBrush(brush)
        contenRect = QRect(0, self.height() - bottomHeight, self.width(), bottomHeight)
        painter.fillRect(contenRect, brush)
        painter.restore()
    def keyPressEvent(self, event):
        keyEvent = QKeyEvent(event)
        if keyEvent.key() == Qt.Key_Enter or keyEvent.key() == Qt.Key_Return:
            self.on_pushButtonChPw_clicked()

