#coding: utf-8
import public, db, re, os, time
import zipfile, sys

panelPath = os.getenv('BT_PANEL')
os.chdir(panelPath)
sys.path.insert(0, panelPath + "/class/")


class panelBackup:

    bin_file = None
    def __init__(self):
        self.get_bin_file()

    def get_bin_file(self):
        
        self.bin_file = panelPath + '/btPanel.exe'
        if not os.path.exists(self.bin_file):
            self.bin_file = panelPath + "/aaPanel.exe"

        if not os.path.exists(self.bin_file):
            self.bin_file = panelPath + '/btPanel'

    def get_backup_path(self):
        backup_path = public.M('config').where("id=?", (1, )).getField('backup_path')

        return backup_path

    #备份网站
    def backupSite(self, name):

        shell = "{} --tools backup_site {}".format(self.bin_file, name)
        res = public.ExecShell(shell)[0]
        print(res)

        res = res.replace('\\', '/')
        backup_path = self.get_backup_path().replace('\\', '/')

        pattern = re.compile(r'{}\/.*\.zip'.format(backup_path))

        filename = re.search(pattern, res).group()
        if not os.path.exists(filename):
            return ""
        return filename

    #备份数据库
    def backupDatabase(self, name):
       
        shell = "{} --tools backup_database {}".format(self.bin_file, name)
        res = public.ExecShell(shell)[0]
        print(res)

        res = res.replace('\\', '/')
        backup_path = self.get_backup_path().replace('\\', '/')

        pattern = re.compile(r'{}\/.*'.format(backup_path))

        filename = re.search(pattern, res).group()
        if not os.path.exists(filename):
            return ""
        return filename

    #备份指定目录
    def backupPath(self, path):
        shell = "{} --tools backup_path {}".format(self.bin_file, path)
        res = public.ExecShell(shell)[0]
        print(res)

        res = res.replace('\\', '/')
        backup_path = self.get_backup_path().replace('\\', '/')

        pattern = re.compile(r'{}\/.*\.zip'.format(backup_path))

        filename = re.search(pattern, res).group()
        if not os.path.exists(filename):
            return ""
        return filename
