#!/usr/bin/python
#coding: utf-8
#-----------------------------
# 安装脚本
#-----------------------------

import sys,os,shutil,re
panelPath = os.getenv('BT_PANEL')
os.chdir(panelPath)
sys.path.append("class/")
import public,tarfile

class panel_mongodb:
    _name = 'mongodb'
    _version = None
    _setup_path = None
    __path = panelPath + '/plugin/' + _name

    def __init__(self,name,version,setup_path):
        self._name = name
        self._version = version
        self._setup_path = setup_path

    def install_soft(self,downurl):

        if public.get_server_status(self._name) >= 0:  public.delete_server(self._name)
     
        try:
            import pymongo
        except :
            os.system(public.get_run_pip("[PIP] install pymongo"))
        path = self._setup_path + '/' + self._name
        if not os.path.exists(path):  os.makedirs(path)
        if not os.path.exists(self.__path): os.makedirs(self.__path)            

        temp = self._setup_path + '/temp/mongodb.zip'       
     
        public.downloadFileByWget(downurl + '/win/mongodb/'+ self._version +'.zip',temp)
        if not os.path.exists(temp): return public.returnMsg(False,'文件下载失败,请检查网络!');

        public.bt_print('正在解压文件.')     
        import zipfile
        zip_file = zipfile.ZipFile(temp)  
        for names in zip_file.namelist():              
            zip_file.extract(names,self._setup_path)            
        zip_file.close()
        
        public.bt_print('正在配置mongodb配置文件.')      
        iniPath = path + '/config.conf'
        config = public.readFile(iniPath).replace('[PATH]', public.format_path(self._setup_path))
        public.writeFile(iniPath,config)
        if os.path.exists(path + '/version.pl'): os.remove(path + '/version.pl')       

        pluginUrl = downurl + '/win/install/plugin/' + self._name
        fileList = ['mongodb_main.py','index.html','info.json','icon.png']
        for f in fileList:
            print(pluginUrl + '/' + f,self.__path + '/' + f)

            public.downloadFile(pluginUrl + '/' + f,self.__path + '/' + f)
            if not os.path.exists(self.__path + '/' + f):
                return public.returnMsg(False,'文件下载失败!');

        shell = '%s && cd %s/bin && mongod -config %s/config.conf --install --serviceName "mongodb"' % (self._setup_path[0:2],public.format_path(self._setup_path + '/mongodb'),public.format_path(self._setup_path + '/mongodb'))
        print(shell)
        os.system(shell)
        if public.get_server_status(self._name) >= 0:  
            if  public.set_server_status(self._name,"start"):
                public.bt_print('mongodb安装成功。!')
                return public.returnMsg(True,'mongodb安装成功!');           
        
        return public.returnMsg(False,'安装失败!');

    def uninstall_soft(self):
        if public.get_server_status(self._name) >= 0:  public.delete_server(self._name)

        shutil.rmtree(self.__path)
        return public.returnMsg(True,'卸载成功!');

    def update_soft(self,downurl):
        path = self._setup_path + '\\mongodb'


        sfile = '%s/config.conf' % (path)
        dfile = '%s/config.conf.backup' % (path)
        shutil.copy (sfile,dfile)

        rRet = self.install_soft(downurl)
        if not rRet['status'] : rRet;
        if public.set_server_status(self._name,'stop'):
            shutil.copy(dfile,sfile)
            os.remove(dfile);
            if public.set_server_status(self._name,'start'):
                 return public.returnMsg(True,'更新成功!');
        return public.returnMsg(False,'更新失败!');
