#!/usr/bin/env python
# Copyright 2019-2020 VMware, Inc.  All rights reserved. -- VMware Confidential

#
# This is the firstboot script for the API Gateway.
# It registers the API Gateway into the Lookup Service.
#
import os
import sys
import re

from cis.defaults import get_component_home_dir
from cis.firstboot import FirstBoot
from cis.tools import wait_for_install_parameter
from cis.utils import log, write_props_to_file, FileBuffer
from cis.vecs import vmafd_machine_id


CISREG_PATH = os.path.join(get_component_home_dir('cm'), 'bin')
sys.path.append(CISREG_PATH)

from cloudvmcisreg import VecsKeyStore, cloudvm_sso_cm_register


APIGW_COMP_NAME = "apigw"
APIGW_SHARED_SOLUTION_USER = "vsphere-webclient"


class APIGatewayFB(FirstBoot):
   """
   Barebone first boot.

   API Gateway is not a separate service. This class is only used to get
   the full solution user name.
   """
   def __init__(self):
      super(APIGatewayFB, self).__init__(APIGW_COMP_NAME, APIGW_SHARED_SOLUTION_USER)


# Executed during a firstboot run to tegister API Gateway with Lookup Service
def register_with_cm(install_dir, http_port):
   apigwFb = APIGatewayFB()

   do_register_with_cm(install_dir, http_port, apigwFb.get_soluser_id(), apigwFb.get_soluser_name())


# Executed during a B2B upgrade patch to register API Gateway with Lookup Service
def patch_register_with_cm():
   install_dir = "/usr/lib/vmware-vsphere-ui"
   http_port = wait_for_install_parameter('vsphere-ui.int.port2')

   soluser_id = '%s-%s' % (APIGW_SHARED_SOLUTION_USER, vmafd_machine_id())
   soluser_name = APIGW_SHARED_SOLUTION_USER

   do_register_with_cm(install_dir, http_port, soluser_id, soluser_name)


# Register API Gateway with Lookup Service
def do_register_with_cm(install_dir, http_port, soluser_id, soluser_name):
   cisregSpec = os.path.join(install_dir, 'scripts', 'config', 'apigw-spec.properties')

   if not os.path.exists(cisregSpec):
      log("The API Gateway bundle is not available in the H5C deployment. Unable to register.")
      return

   if not getServiceId(cisregSpec):
      keystore = VecsKeyStore(soluser_name)

      vmdirDomainName = wait_for_install_parameter('vmdir.domain-name')
      soluser_upn = '%s@%s' % (soluser_id, vmdirDomainName)
      dynVars = {'apigw.solutionuser.name' : escape_property_value(soluser_upn),
                 'http_port': http_port
      }

      log('Registering API Gateway Endpoint into the Lookup Service')
      cloudvm_sso_cm_register(keystore, cisregSpec, soluser_name, dynVars)
      log('Successfully registered API Gateway Endpoint into the Lookup Service')
   else:
      log('API Gateway Endpoint is already registered into Lookup Service. No need to register again.')


def getServiceId(file_dir):
   file_buffer = FileBuffer()
   file_buffer.readFile(file_dir)
   serviceId = get_property(file_buffer, 'cmreg.serviceid')
   return serviceId;


def get_property(file_buffer, key):
   pat = "^(\s*" + re.escape(key) + "\s*=\s*)(.*)"
   for line in file_buffer.getBufferContents():
      m = re.search(pat, line)
      if m:
         return m.group(2).strip()
   return None


def escape_property_value(value):
   """
   Escape all '\' chars.
   Note: we need to escape all backslash char since they are treated by java as a special
   char.
   """
   return value.replace('\\', '\\\\')
