# Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
import pmm_config
import pmmcli_config
import os
import subproc
import shutil
from pmmcli_exceptions import PMMUtilityException
import sys

class GuidsFixer:
    def run(restore_specification, session_path):
        cmd = subproc.CmdLine(pmm_config.plesk_runner())
        for plesk_runner_arg in pmm_config.plesk_runner_args():
            cmd.arg(plesk_runner_arg)
        cmd.arg(pmm_config.pmm_conflict_detector())
        cmd.arg('--fix-guids')
        restore_specification_arg = '--restore-specification=' + restore_specification
        cmd.arg(restore_specification_arg)
        session_path_arg = '--session-path=' + session_path
        cmd.arg(session_path_arg)
        errcode = 0
        try:
            cmd.spawn()
        except subproc.NonzeroExitException, x:
            errcode = x.exitcode
            if errcode != 254:
                raise PMMUtilityException('Guids Fixer', x)
        return errcode != 0
    
    run = staticmethod(run)


class NamesFixer:
    def run(restore_specification, session_path):
        cmd = subproc.CmdLine(pmm_config.plesk_runner())
        for plesk_runner_arg in pmm_config.plesk_runner_args():
            cmd.arg(plesk_runner_arg)
        cmd.arg(pmm_config.pmm_conflict_detector())
        cmd.arg('--fix-names')
        restore_specification_arg = '--restore-specification=' + restore_specification
        cmd.arg(restore_specification_arg)
        session_path_arg = '--session-path=' + session_path
        cmd.arg(session_path_arg)
        errcode = 0
        try:
            cmd.spawn()
        except subproc.NonzeroExitException, x:
            raise PMMUtilityException('Names Fixer', x)
        return
    
    run = staticmethod(run)


class ConflictDetector:
    def run(owner_guid, conflicts_description_out,session_path, dump_index_file):
        cmd = subproc.CmdLine(pmm_config.plesk_runner())
        for plesk_runner_arg in pmm_config.plesk_runner_args():
            cmd.arg(plesk_runner_arg)
        cmd.arg(pmm_config.pmm_conflict_detector())
        cmd.arg('--detect-conflicts')
        if owner_guid:
            owner_guid_arg = '--owner-guid=' + owner_guid
            cmd.arg(owner_guid_arg)
        restore_specification_arg = '--restore-specification=' + dump_index_file
        cmd.arg(restore_specification_arg)
        
        conflict_iteration = 0
        conflicts_description_out_based = conflicts_description_out
        while os.path.isfile(conflicts_description_out):
            conflict_iteration += 1
            conflicts_description_out = conflicts_description_out_based + "." + str(conflict_iteration)
        
        if conflicts_description_out_based != conflicts_description_out:
            shutil.copy2(conflicts_description_out_based,conflicts_description_out)
        
        conflicts_description_arg = '--conflicts-description-out=' + conflicts_description_out_based
        cmd.arg(conflicts_description_arg)
        
        session_path_arg = '--session-path=' + session_path
        cmd.arg(session_path_arg)
        
        log_arg = '--log=' + 'conflict-detect.log'
        cmd.arg(log_arg)

        if pmmcli_config.get().force_debug_log() == 1:
            cmd.arg('--debug')
        
        try:
            cmd.spawn()
        except subproc.NonzeroExitException, x:
            raise PMMUtilityException('Conflict Detector', x)
        
        if not os.path.isfile(conflicts_description_out):
            # suppose there is no conflicts found
            return None
        else:
            return conflicts_description_out

    run = staticmethod(run)


class ConflictResolver:
    def run(owner_guid, restore_specification, conflicts_description,conflicts_resolution_rules,session_path, dump_index_file, session_dump_path, extension_filter_file, restore_mode):
        cmd = subproc.CmdLine(pmm_config.plesk_runner())
        for plesk_runner_arg in pmm_config.plesk_runner_args():
            cmd.arg(plesk_runner_arg)
        cmd.arg(pmm_config.pmm_conflict_resolver())
        cmd.arg('--resolve-conflicts')
        if owner_guid:
            owner_guid_arg = '--owner-guid=' + owner_guid
            cmd.arg(owner_guid_arg)
        restore_specification_arg = '--restore-specification=' + dump_index_file
        cmd.arg(restore_specification_arg)
        conflicts_description_arg = '--conflicts-description=' + conflicts_description
        cmd.arg(conflicts_description_arg)
        conflicts_resolution_rules_arg = '--conflicts-resolution-rules=' + conflicts_resolution_rules
        cmd.arg(conflicts_resolution_rules_arg)
        new_restore_specification_arg = '--restore-specification-out=' + session_dump_path
        cmd.arg(new_restore_specification_arg)
        session_path_arg = '--session-path=' + session_path
        cmd.arg(session_path_arg)
        log_arg = '--log=' + 'conflict-resolve.log'
        cmd.arg(log_arg)

        mswindows = (sys.platform == "win32")
        open(extension_filter_file, 'w').close()
        if not mswindows:
            os.chmod(extension_filter_file,0640)
            
        extension_filter_file_arg = '--extension-filter-file-out=' + extension_filter_file
        cmd.arg(extension_filter_file_arg)

        if restore_mode == "migration":
            restore_mode_arg = "--mode=" + restore_mode
            cmd.arg(restore_mode_arg)

        if pmmcli_config.get().force_debug_log() == 1:
            cmd.arg('--debug')
        
        try:
            cmd.spawn()
        except subproc.NonzeroExitException, x:
            raise PMMUtilityException('Conflict Resolver', x)
        
        return restore_specification

    run = staticmethod(run)


class CapabilityInfo:

    @staticmethod
    def runForTransfer(owner_guid, session_path, source_capability_info, capability_info_out):
        cmd = subproc.CmdLine(pmm_config.plesk_runner())
        for plesk_runner_arg in pmm_config.plesk_runner_args():
            cmd.arg(plesk_runner_arg)
        cmd.arg(pmm_config.pmm_conflict_resolver())
        cmd.arg('--check-capability')
        if owner_guid:
            cmd.arg('--owner-guid=' + owner_guid)
        cmd.arg('--session-path=' + session_path)
        cmd.arg('--log=' + 'conflict-resolve.log')
        cmd.arg('--capability-info=' + source_capability_info)
        cmd.arg('--capability-info-out=' + capability_info_out)
        cmd.arg('--used-space-coefficient=' + str(pmmcli_config.get().get_used_space_coefficient()))
        cmd.arg('--max-transfer-download-time=' + str(pmmcli_config.get().get_max_transfer_download_time()))
        cmd.arg('--min-transfer-download-speed=' + str(pmmcli_config.get().get_min_transfer_download_speed()))

        if pmmcli_config.get().force_debug_log() == 1:
            cmd.arg('--debug')

        errorcode = 0
        try:
            cmd.spawn()
        except subproc.NonzeroExitException, x:
            errorcode = x.exitcode
            if errorcode != 254:
                raise PMMUtilityException('Conflict Resolver', x)

        return errorcode

class MssqlNativeBackupMode:

    @staticmethod
    def check(session_path):
        cmd = subproc.CmdLine(pmm_config.plesk_runner())
        for plesk_runner_arg in pmm_config.plesk_runner_args():
            cmd.arg(plesk_runner_arg)
        cmd.arg(pmm_config.pmm_conflict_detector())
        cmd.arg('--check-mssql-native-backup-mode')
        session_path_arg = '--session-path=' + session_path
        cmd.arg(session_path_arg)

        log_arg = '--log=' + 'conflict-resolve.log'
        cmd.arg(log_arg)

        if pmmcli_config.get().force_debug_log() == 1:
            cmd.arg('--debug')

        try:
            cmd.spawn()
        except subproc.NonzeroExitException, x:
            if x.exitcode == 254:
                return True
            raise PMMUtilityException('MSSQL Native backup mode support checker', x)

        return False

class RegisteredRemoteDbServers:
    @staticmethod
    def get(session_path):
        cmd = subproc.CmdLine(pmm_config.plesk_runner())
        for plesk_runner_arg in pmm_config.plesk_runner_args():
            cmd.arg(plesk_runner_arg)
        cmd.arg(pmm_config.pmm_conflict_detector())
        cmd.arg('--get-remote-db-servers')
        session_path_arg = '--session-path=' + session_path
        cmd.arg(session_path_arg)
        try:
            cmd.spawn()
        except subproc.NonzeroExitException, x:
            raise PMMUtilityException('Get registered remote db servers', x)

        return True