# Copyright 2015 VMware, Inc.  All rights reserved. -- VMware Confidential
#
'''
Script responsible to setup environment and execute the pre-patching hook of vCSA
components. The script calls only those components which have been discovered
in prior discovery phase.
'''
import logging
from extensions import Hook
from patch_specs import PatchContext

from vmware_b2b.patching.utils.phase_utils import executeHook, setupStatusAggregator
from vmware_b2b.patching.data.model import PatchPhaseContext

logger = logging.getLogger(__name__)


def prepatch(stageDir, userData, outputFile):
    '''The entry point of prepatch CPO phase.

    The prepatch phase is responsible to setup environment and execute the
    prepatching hook of vCSA components. The patch phase calls only those
    components which have been discovered in prior discovery phase. The prepatch
    phase stops all VMware services before vCSA prepatch hook is executed.

    @param stageDir: global CPO stage directory. All components stage
      directories will be created as sub-directories of global stage directory.
    @type stageDir: str

    @param userData: Customer input, as result of component questions raised
      in @Discovery patching hook.
    @type userData: dict

    @param outputFile: File where the output of the command needs to be written
      to
    @type outputFile: str

    @return: True if the prepatch phase succeed and False otherwise
    @rtype: bool
    '''
    ctx = PatchPhaseContext.load(stageDir)

    hooksToExecute = [Hook.Prepatch]
    if ctx.upgradeType == PatchContext.DISRUPTIVE_UPGRADE:
        # insert it at the start because Expand has to be executed first
        hooksToExecute.insert(0, Hook.Expand)

    with setupStatusAggregator(ctx, outputFile, hooksToExecute) as statusAggregator:
        for hook in hooksToExecute:
            logger.info("Running %s phase", hook)
            if not executeHook(hook, ctx, userData, statusAggregator):
                return False

    return True
