# -*- coding: utf-8 -*-

# Copyright 2014-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import sys
from os import path
import time
import glob
import pickle
from calculate.core.datavars import DataVarsCore
from calculate.lib.cl_lang import setLocalTranslate

_ = lambda x: x
setLocalTranslate('cl_core3', sys.modules[__name__])


def restart(process_dict):
    """
    Функция отслеживает необходимость перезапуска демона и
    перезапускает init.d/calculate-core
    """
    #    cert_live = 10080
    # Get value of period and lifetime session from DataVars
    ob = DataVarsCore()
    ob.importCore()

    if not ob.flIniFile():
        return

    restart_file = ob.Get('cl_core_restart_path')
    stop_file = ob.Get('cl_core_dbus_stop_path')
    service_name = "calculate-core"
    if path.exists(restart_file):
        os.unlink(restart_file)

    while True:
        if path.exists(restart_file) and not process_dict:
            # Частота проверки
            if path.exists(stop_file):
                kill_server()
            else:
                os.system('/etc/init.d/%s restart &>/dev/null &' % service_name)
            return
        time.sleep(1)

def kill_server():
    import os
    os.kill(os.getpid(), 2)


def dbus_stop(process_dict, sids_dn, base_obj):
    """
    Функция отслеживает необходимость остнова демона если
    нет активной сессии и демон запускался через dbus
    """
    #    cert_live = 10080
    # Get value of period and lifetime session from DataVars
    ob = DataVarsCore()
    ob.importCore()

    if not ob.flIniFile():
        return

    stop_file = ob.Get('cl_core_dbus_stop_path')
    stop_server = False

    while True:
        if path.exists(stop_file) and not process_dict:
            with base_obj.sid_locker:
                for fn in glob.glob("%s/*.sid" % sids_dn):
                    if os.path.isfile(fn):
                        with open(fn) as fd:
                            sid_inf = pickle.load(fd)
                            # обнаружена рабочая сессия
                            if sid_inf[2] != 1:
                                stop_server = True
                                break
                else:
                    # не выключаем сессию до того пока не пройдёт хотя бы одна сессия
                    if stop_server:
                        # остановить сервер
                        try:
                            os.unlink(stop_file)
                        except:
                            pass
                        kill_server()
        time.sleep(5)
