#!/usr/bin/env python

"""
This file is used to create CLS trust store
"""

from __future__ import absolute_import
import base64
import logging
import os
import sys
import shutil

if not os.environ['VMWARE_PYTHON_PATH'] in sys.path:
    sys.path.append(os.environ['VMWARE_PYTHON_PATH'])
# Prefer the files in the directory of this file when importing. This is important during patching
# as the VC can have older copies of other files in /usr/lib/vmware-content-library
sys.path.insert(0, os.path.dirname(__file__))
from cis.defaults import get_cis_install_dir
from cis.utils import def_by_os, log, gen_random_pwd, invoke_command
from cis.tools import get_keytool
from install_common import VCDE_COMPONENT_NAME

# The following path should be included in VMWARE_PYTHON_PATH
sys.path.append(def_by_os("%s/vmware-%s/bin" % (get_cis_install_dir(), "cm"),
                          os.path.join(get_cis_install_dir(), "cm", "bin")))


__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright (c) 2021 VMware, Inc. All rights reserved.'

logger = logging.getLogger(__name__)

##########################################################################


class CLSTrustStore():

    """
     Creates the content library trust store.
     Skips if the store is present.
    """
    def __init__(self, vdc_cfg_dir):
        """
         @param vdc_cfg_dir: the directory to create and store cl trust store.
        """
        self.vdc_cfg_dir = vdc_cfg_dir

    def setup_cls_truststore(self):
        """Setup the content library trust store"""
        truststore_default_pwd = 'p' + gen_random_pwd(10, False)
        cl_truststore_name = 'truststore.bks'
        content_library_truststore_file = os.path.join(self.vdc_cfg_dir,
                                                       cl_truststore_name)

        # do not do anything if the keystore already exists.
        if os.path.exists(content_library_truststore_file):
            return

        log("Creating a default truststore for content-library trust manager "
            "at: %s" % content_library_truststore_file)

        # VMware root is by default trusted by VC, so seeding it to the truststore
        # This is due to the limitation in keytool to create an empty truststore.
        vmware_cert_alias = 'vmware_signed'

        '''
        keytool -import -file /var/lib/vmware/vmca/root.cer -alias "vmware_signed"
         -storepass changeit -keystore /etc/vmware-content-library/truststore.bks
          -deststoretype BCFKS -noprompt
          -provider org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider
          -providerpath /usr/java/jre-vmware/lib/ext-fips/bc-fips-1.0.2.1.jar
        '''
        cmd = [get_keytool(),
               '-import',
               '-file', '/var/lib/vmware/vmca/root.cer',
               '-alias', vmware_cert_alias,
               '-storepass', truststore_default_pwd,
               '-keystore', content_library_truststore_file,
               '-deststoretype', 'BCFKS',
               '-provider', 'org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider',
               '-providerpath', '/usr/java/jre-vmware/lib/ext-fips/bc-fips-1.0.2.1.jar',
               '-noprompt']
        invoke_command(cmd)
        # Change the ownership to content-library user
        shutil.chown(content_library_truststore_file, VCDE_COMPONENT_NAME)

        from install_common import get_vdc_properties_path
        with open(get_vdc_properties_path(self.vdc_cfg_dir), 'a') as vdc_properties:
            vdc_properties.write('cl.truststore.path=%s\n' % content_library_truststore_file)
            vdc_properties.write('cl.truststore.pwd=%s\n' % truststore_default_pwd)
            vdc_properties.write('cl.truststore.type=BCFKS\n')

        # Create symlinks required for VCHA
        vcha_symlinks_dir = os.getenv('VMWARE_VCHA_SMALLFILES_DIR')
        cls_vcha_files_dir = os.path.join(vcha_symlinks_dir, 'content-library')
        if os.path.exists(cls_vcha_files_dir):
            trust_store_symlink_path = os.path.join(cls_vcha_files_dir, cl_truststore_name)
            os.symlink(content_library_truststore_file, trust_store_symlink_path)
