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

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

class panel_memcached:
    _name = 'memcached'
    _version = None
    _setup_path = None

    def __init__(self,name,version,setup_path): 
        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)

        temp = self._setup_path + '/temp/memcached.zip'

        cloud_path = downurl + '/win/memcached/memcached' + self._version + '.zip'
        if self.get_os_version().find('2008') >= 0:
            self._version = '1.4'
            cloud_path = downurl + '/win/memcached/memcached1.4.zip'
            public.bt_print('windows 2008将不支持memcached1.6，程序将自动为您安装memcached1.4.')

        public.downloadFile(cloud_path,temp)
        if not os.path.exists(temp): return public.returnMsg(False,'文件下载失败,请检查网络!');
 
        import zipfile
        zip_file = zipfile.ZipFile(temp)  
        for names in zip_file.namelist():   
            zip_file.extract(names,self._setup_path)    

        rRet = public.create_server(self._name,self._name,self._setup_path + '\\memcached\\memcached_server.exe','',"Memcached 是一个高性能的分布式内存对象缓存系统，用于动态Web应用以减轻数据库负载")
        if public.get_server_status(self._name) == 0:
            if public.set_server_status(self._name,'start'): 
                public.bt_print('memcached启动成功.')
            else:
                return public.returnMsg(False,'启动失败，请检查配置文件是否错误!');

        config_path = self._setup_path + '/memcached/config.json'
        data = {}
        data['bind'] = '-l 127.0.0.1'
        data['port']  = '-p 11211'
        data['cachesize'] = '-m 256'
        data['minsize'] = '-n 48'
        data['maxconn'] = '-c 10000'
        data['factor'] = '-f 1.25'

        public.writeFile(self._setup_path + '/memcached/runservice','-l 127.0.0.1 -p 11211 -m 256 -n 48 -f 1.25 -c 10000')
        public.writeFile(config_path,json.dumps(data))
        public.bt_print('memcached安装成功.')
        if self.get_os_version().find('2008') >= 0:
            public.bt_print('windows 2008将不支持memcached1.6，程序将自动为您安装memcached1.4.')
        return public.returnMsg(True,'安装成功!');
   

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

        return public.returnMsg(True,'卸载成功!');


    def get_registry_value(self,key, subkey, value):
        import winreg
        key = getattr(winreg, key)
        handle = winreg.OpenKey(key, subkey)
        (value, type) = winreg.QueryValueEx(handle, value)
        return value

    def get_os_version(self):
        def get(key):
            return self.get_registry_value("HKEY_LOCAL_MACHINE", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", key)
        v = get("ProductName")
        build = get("CurrentBuildNumber")
        os_version = "%s (build) %s" % (v, build)

        return os_version


    def update_soft(self,downurl):
        path = self._setup_path + '/memcached'
        sfile = path +'/config.json'
        dfile = path + '/config.json.backup'
        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,'更新失败!');



