"""
Copyright 2017 VMware, Inc.  All rights reserved.
-- VMware Confidential
"""

"""This module contains various helper methods for vSAN DPS B2B Patching
"""

import sys
import os

vmware_libs_dir = os.environ['VMWARE_PYTHON_PATH']
if vmware_libs_dir not in sys.path:
   sys.path.append(vmware_libs_dir)

import logging
import os_utils
from os_utils import executeCommand

logger = logging.getLogger(__name__)

DPS_FB_SCRIPT = "/usr/lib/vmware-vpx/firstboot/vsandps_firstboot.py"

def is_valid_version():
   """Verify whether to participate in patch upgrade or not.
   """
   # If DPS firstboot script does not exist, then skip B2B upgrade for DPS.
   return os.path.isfile(DPS_FB_SCRIPT)


def do_patching():
   """Perform DPS patching by running DPS firstboot
      python /usr/lib/vmware-vpx/firstboot/vsandps_firstboot.py --action=firstboot
   """
   if is_valid_version():
      args = ['python']
      args.append(DPS_FB_SCRIPT)
      args.append('--action=firstboot')

      logger.info('command: %s' % args)
      stdout, stderr, rc = executeCommand(args)
      logger.info('rc: %s, stdout: %s, stderr: %s' % (rc, stdout, stderr))
      if rc != 0:
         logger.error("An error occurred. Result code: [%s],\nstd err: [%s]\nstd out:[%s]" %
                      (rc, stderr, stdout))
         raise Exception("vSAN DPS patch failed.")
      else:
         logger.info("vSAN Data Protection service successfully patched.")
   else:
      logger.info("Could not find DPS firstboot script. Do nothing.")
