#
# Copyright 2015 Naver Corp.
#
# 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 constant as c
import config
import time
import os
import util
import smr_mgmt
import json
import default_cluster


def setup_binaries( clusters, skip_copy_binaries, opt_32bit_binary_test ):
    if not os.path.exists( c.homedir ):
        os.mkdir( c.homedir )
    if not os.path.exists( c.logdir ):
        os.mkdir( c.logdir )

    # resource caching/skip structures
    server_id_dict = {} # boolean value
    if skip_copy_binaries is False:
        for cluster in clusters:
            for server in cluster['servers']:
                id = server['id']
                if server_id_dict.has_key(id):
                    continue
                server_id_dict[id] = True

                if copy_binaries(id, opt_32bit_binary_test) is not 0:
                    util.log('failed to copy_binaries, server_id: %d' % server['id'])
                    return -1
    util.log('initialize done')
    return 0


def cleanup_zookeeper_root():
    max_try = 20
    for i in range( max_try ):
        print 'try cleanup zookeeper, i:%d' % i

        if util.zk_cmd( 'get /RC' )['exitcode'] == 'ZK_NO_NODE':
            return 0

        ret = util.zk_cmd( 'rmr /RC' )
        if ret['exitcode'] == 'OK':
            return 0
        else:
            util.log('failed to clean up zookeeper, ret:%s' % ret)
        time.sleep(0.2)
    return -1


def cleanup_processes():
    ret = util.killps_y( 'smr-replicator' )
    if ret is not 0:
        util.log( 'failed to kill smr' )
        return -1

    ret = util.killps_y( 'redis-arc' )
    if ret is not 0:
        util.log( 'failed to kill redis-arc' )
        return -1

    ret = util.killps_y( 'redis-gateway' )
    if ret is not 0:
        util.log( 'failed to kill redis-gateway' )
        return -1

    ret = util.killps_y( 'confmaster-' )
    if ret is not 0:
        util.log( 'failed to kill confmaster' )
        return -1

    return 0


def cleanup_pgs_log_and_ckpt( cluster_name, server ):
    ret = util.delete_smr_log_dir( server['id'], server['smr_base_port'] )
    if ret is not 0:
        util.log('failed to delete smr log dir')
        return -1

    ret = util.delete_redis_check_point( server['id'] )
    if ret is not 0:
        util.log('failed to delete redis check point')
        return -1

    return 0


def request_to_start_cm( id, port, context='' ):
    ret = util.start_confmaster( id, port, context )
    if ret is not 0:
        util.log('failed to start_confmaster. id:%d, port:%d, context;"%s"' % (id, port, context))
        return -1