# coding: utf-8
# Copyright (c) 2016, 2026, Oracle and/or its affiliates.  All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
# NOTE: This class is auto generated by OracleSDKGenerator. DO NOT EDIT. API Version: release

from __future__ import print_function
import click
import oci  # noqa: F401
import six  # noqa: F401
import sys  # noqa: F401
from oci_cli import cli_constants  # noqa: F401
from oci_cli import cli_util
from oci_cli import json_skeleton_utils
from oci_cli import custom_types  # noqa: F401
from oci_cli.aliasing import CommandGroupWithAlias
from services.key_management.src.oci_cli_key_management.generated import kms_service_cli


@click.command(cli_util.override('kms_hsm_cluster.kms_hsm_cluster_root_group.command_name', 'kms-hsm-cluster'), cls=CommandGroupWithAlias, help=cli_util.override('kms_hsm_cluster.kms_hsm_cluster_root_group.help', """Use the Key Management API to manage vaults and keys. For more information, see [Managing Vaults] and [Managing Keys]."""), short_help=cli_util.override('kms_hsm_cluster.kms_hsm_cluster_root_group.short_help', """Vault Key Management API"""))
@cli_util.help_option_group
def kms_hsm_cluster_root_group():
    pass


@click.command(cli_util.override('kms_hsm_cluster.hsm_cluster_group.command_name', 'hsm-cluster'), cls=CommandGroupWithAlias, help="""Dedicated KMS-HSM Cluster Management""")
@cli_util.help_option_group
def hsm_cluster_group():
    pass


@click.command(cli_util.override('kms_hsm_cluster.hsm_partition_group.command_name', 'hsm-partition'), cls=CommandGroupWithAlias, help="""Dedicated KMS-HSM Partition Management""")
@cli_util.help_option_group
def hsm_partition_group():
    pass


kms_service_cli.kms_service_group.add_command(kms_hsm_cluster_root_group)
kms_hsm_cluster_root_group.add_command(hsm_cluster_group)
kms_hsm_cluster_root_group.add_command(hsm_partition_group)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.cancel_hsm_cluster_deletion.command_name', 'cancel-hsm-cluster-deletion'), help=u"""Cancels deletion of specified HSM Cluster, restores it and associated HSM partitions to pre-deletion states. \n[Command Reference](cancelHsmClusterDeletion)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "INITIALIZATION_REQUIRED", "INITIALIZING", "ACTIVATION_REQUIRED", "ACTIVATING", "ACTIVE", "DELETING", "DELETED", "PENDING_DELETION", "SCHEDULING_DELETION", "CANCELLING_DELETION"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state CREATING --wait-for-state CANCELLING_DELETION would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""")
@cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""")
@cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'HsmCluster'})
@cli_util.wrap_exceptions
def cancel_hsm_cluster_deletion(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, hsm_cluster_id, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.cancel_hsm_cluster_deletion(
        hsm_cluster_id=hsm_cluster_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_hsm_cluster') and callable(getattr(client, 'get_hsm_cluster')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds

                click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_hsm_cluster(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.change_hsm_cluster_compartment.command_name', 'change-compartment'), help=u"""Moves a HSM Cluster resource to a different compartment within the same tenancy. \n[Command Reference](changeHsmClusterCompartment)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the hsm cluster to.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def change_hsm_cluster_compartment(ctx, from_json, hsm_cluster_id, compartment_id, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}
    _details['compartmentId'] = compartment_id

    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.change_hsm_cluster_compartment(
        hsm_cluster_id=hsm_cluster_id,
        change_hsm_cluster_compartment_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.create_hsm_cluster.command_name', 'create'), help=u"""Creates a new HSM cluster resource. \n[Command Reference](createHsmCluster)""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment where you want to create this HSM cluster resource.""")
@cli_util.option('--display-name', required=True, help=u"""A user-friendly display name for the HSM cluster resource. It does not have to be unique, and it is changeable. Avoid entering confidential information.""")
@cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--audit-log-config', type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "INITIALIZATION_REQUIRED", "INITIALIZING", "ACTIVATION_REQUIRED", "ACTIVATING", "ACTIVE", "DELETING", "DELETED", "PENDING_DELETION", "SCHEDULING_DELETION", "CANCELLING_DELETION"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state CREATING --wait-for-state CANCELLING_DELETION would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""")
@cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""")
@cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'key_management', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'key_management', 'class': 'dict(str, string)'}, 'audit-log-config': {'module': 'key_management', 'class': 'AuditLoggingConfig'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'key_management', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'key_management', 'class': 'dict(str, string)'}, 'audit-log-config': {'module': 'key_management', 'class': 'AuditLoggingConfig'}}, output_type={'module': 'key_management', 'class': 'HsmCluster'})
@cli_util.wrap_exceptions
def create_hsm_cluster(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, display_name, defined_tags, freeform_tags, audit_log_config):

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}
    _details['compartmentId'] = compartment_id
    _details['displayName'] = display_name

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags)

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags)

    if audit_log_config is not None:
        _details['auditLogConfig'] = cli_util.parse_json_parameter("audit_log_config", audit_log_config)

    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.create_hsm_cluster(
        create_hsm_cluster_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_hsm_cluster') and callable(getattr(client, 'get_hsm_cluster')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds

                click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_hsm_cluster(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.disable_audit_mgmt_logging.command_name', 'disable-audit-mgmt-logging'), help=u"""Disables management audit logging for the given HSM Cluster resource. This requires the Crypto Officer (CO) password. This operation is idempotent: if audit logging is already disabled, the call is a no-op and returns success. \n[Command Reference](disableAuditMgmtLogging)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def disable_audit_mgmt_logging(ctx, from_json, hsm_cluster_id, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.disable_audit_mgmt_logging(
        hsm_cluster_id=hsm_cluster_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.download_certificate_signing_request.command_name', 'download-certificate-signing-request'), help=u"""Retrieves the certificate signing request for the designated HSM Cluster resource. \n[Command Reference](downloadCertificateSigningRequest)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def download_certificate_signing_request(ctx, from_json, hsm_cluster_id, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.download_certificate_signing_request(
        hsm_cluster_id=hsm_cluster_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.enable_audit_mgmt_logging.command_name', 'enable-audit-mgmt-logging'), help=u"""Validates that the Dynamic Group and bucket policy supplied during EnableAuditLogging / CreateHsmCluster are now in place. If the cluster is in WAITING_FOR_CUSTOMER, and validation is successful, status is progressed and a work request is started. If the cluster has already progressed past that gate, the call is idempotent and returns 202 with the current cluster representation. \n[Command Reference](enableAuditMgmtLogging)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'EnableAuditMgmtLogging'})
@cli_util.wrap_exceptions
def enable_audit_mgmt_logging(ctx, from_json, hsm_cluster_id, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.enable_audit_mgmt_logging(
        hsm_cluster_id=hsm_cluster_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.get_hsm_cluster.command_name', 'get'), help=u"""Retrieves configuration details for the specified HSM Cluster resource.

As a provisioning operation, this call is subject to a Key Management limit that applies to the total number of requests across all provisioning read operations. Key Management might throttle this call to reject an otherwise valid request when the total rate of provisioning read operations exceeds 10 requests per second for a given tenancy. \n[Command Reference](getHsmCluster)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'HsmCluster'})
@cli_util.wrap_exceptions
def get_hsm_cluster(ctx, from_json, hsm_cluster_id):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.get_hsm_cluster(
        hsm_cluster_id=hsm_cluster_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@hsm_partition_group.command(name=cli_util.override('kms_hsm_cluster.get_hsm_partition.command_name', 'get'), help=u"""Retrieves HSM partition details for the specified HSM cluster. \n[Command Reference](getHsmPartition)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--hsm-partition-id', required=True, help=u"""The OCID of the HSM Partition. This is a unique identifier which each hsmPartition will have.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'HsmPartition'})
@cli_util.wrap_exceptions
def get_hsm_partition(ctx, from_json, hsm_cluster_id, hsm_partition_id):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    if isinstance(hsm_partition_id, six.string_types) and len(hsm_partition_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-partition-id cannot be whitespace or empty string')

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.get_hsm_partition(
        hsm_cluster_id=hsm_cluster_id,
        hsm_partition_id=hsm_partition_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.get_pre_co_user_credentials.command_name', 'get-pre-co-user-credentials'), help=u"""Retrieves Pre Crypto Officer user credentials for the specified HSM cluster. \n[Command Reference](getPreCoUserCredentials)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'PreCoUserCredentials'})
@cli_util.wrap_exceptions
def get_pre_co_user_credentials(ctx, from_json, hsm_cluster_id):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.get_pre_co_user_credentials(
        hsm_cluster_id=hsm_cluster_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.initiate_audit_logging.command_name', 'initiate-audit-logging'), help=u"""Initiates the process of enabling audit logs for a HSM cluster resource by taking in the required parameters. \n[Command Reference](initiateAuditLogging)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--bucket-name', required=True, help=u"""The bucket name to which audit logs will be stored.""")
@cli_util.option('--namespace', required=True, help=u"""The namespace under bucket to which audit logs will be stored.""")
@cli_util.option('--compartment-id', required=True, help=u"""The compartmentId [OCID] under namespace to which audit logs will be stored.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'AuditLogging'})
@cli_util.wrap_exceptions
def initiate_audit_logging(ctx, from_json, hsm_cluster_id, bucket_name, namespace, compartment_id, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}
    _details['bucketName'] = bucket_name
    _details['namespace'] = namespace
    _details['compartmentId'] = compartment_id

    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.initiate_audit_logging(
        hsm_cluster_id=hsm_cluster_id,
        initiate_audit_logging_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.list_hsm_clusters.command_name', 'list'), help=u"""Lists all HSM cluster resources contained within the specified compartment.

As a provisioning operation, this call is subject to a Key Management limit that applies to the total number of requests across all provisioning read operations. Key Management might throttle this call to reject an otherwise valid request when the total rate of provisioning read operations exceeds 10 requests per second for a given tenancy. \n[Command Reference](listHsmClusters)""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of items to return in a paginated \"List\" call.""")
@cli_util.option('--page', help=u"""The value of the `opc-next-page` response header from the previous \"List\" call.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can specify only one sort order. The default order for `TIMECREATED` is descending. The default order for `DISPLAYNAME` is ascending.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`).""")
@cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""")
@cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'HsmClusterCollection'})
@cli_util.wrap_exceptions
def list_hsm_clusters(ctx, from_json, all_pages, page_size, compartment_id, limit, page, sort_by, sort_order):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')

    kwargs = {}
    if limit is not None:
        kwargs['limit'] = limit
    if page is not None:
        kwargs['page'] = page
    if sort_by is not None:
        kwargs['sort_by'] = sort_by
    if sort_order is not None:
        kwargs['sort_order'] = sort_order
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

        result = cli_util.list_call_get_all_results(
            client.list_hsm_clusters,
            compartment_id=compartment_id,
            **kwargs
        )
    elif limit is not None:
        result = cli_util.list_call_get_up_to_limit(
            client.list_hsm_clusters,
            limit,
            page_size,
            compartment_id=compartment_id,
            **kwargs
        )
    else:
        result = client.list_hsm_clusters(
            compartment_id=compartment_id,
            **kwargs
        )
    cli_util.render_response(result, ctx)


@hsm_partition_group.command(name=cli_util.override('kms_hsm_cluster.list_hsm_partitions.command_name', 'list'), help=u"""Lists all HSM partitions within the specified HSM Cluster resource. \n[Command Reference](listHsmPartitions)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of items to return in a paginated \"List\" call.""")
@cli_util.option('--page', help=u"""The value of the `opc-next-page` response header from the previous \"List\" call.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can specify only one sort order. The default order for `TIMECREATED` is descending. The default order for `DISPLAYNAME` is ascending.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`).""")
@cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["ACTIVE", "INACTIVE", "ACTIVATING", "ACTIVATION_REQUIRED", "SCHEDULING_DELETION", "PENDING_DELETION", "DELETING", "DELETED"]), help=u"""A filter that returns only resources that match the specified lifecycle state. The state value is case-insensitive.""")
@cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""")
@cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'HsmPartitionCollection'})
@cli_util.wrap_exceptions
def list_hsm_partitions(ctx, from_json, all_pages, page_size, hsm_cluster_id, limit, page, sort_by, sort_order, lifecycle_state):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if limit is not None:
        kwargs['limit'] = limit
    if page is not None:
        kwargs['page'] = page
    if sort_by is not None:
        kwargs['sort_by'] = sort_by
    if sort_order is not None:
        kwargs['sort_order'] = sort_order
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

        result = cli_util.list_call_get_all_results(
            client.list_hsm_partitions,
            hsm_cluster_id=hsm_cluster_id,
            **kwargs
        )
    elif limit is not None:
        result = cli_util.list_call_get_up_to_limit(
            client.list_hsm_partitions,
            limit,
            page_size,
            hsm_cluster_id=hsm_cluster_id,
            **kwargs
        )
    else:
        result = client.list_hsm_partitions(
            hsm_cluster_id=hsm_cluster_id,
            **kwargs
        )
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.schedule_hsm_cluster_deletion.command_name', 'schedule-hsm-cluster-deletion'), help=u"""Schedules HSM cluster for deletion, update its lifecycle state to 'PENDING_DELETION' and deletes it after the retention period. \n[Command Reference](scheduleHsmClusterDeletion)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--time-of-deletion', type=custom_types.CLI_DATETIME, help=u"""An optional property indicating when to delete the HsmCluster resource, expressed in [RFC 3339] timestamp format. The specified time must be between 7 and 30 days from the time when the request is received. If this property is missing, it will be set to 30 days from the time of the request by default.""" + custom_types.CLI_DATETIME.VALID_DATETIME_CLI_HELP_MESSAGE)
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "INITIALIZATION_REQUIRED", "INITIALIZING", "ACTIVATION_REQUIRED", "ACTIVATING", "ACTIVE", "DELETING", "DELETED", "PENDING_DELETION", "SCHEDULING_DELETION", "CANCELLING_DELETION"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state CREATING --wait-for-state CANCELLING_DELETION would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""")
@cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""")
@cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'HsmCluster'})
@cli_util.wrap_exceptions
def schedule_hsm_cluster_deletion(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, hsm_cluster_id, time_of_deletion, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}

    if time_of_deletion is not None:
        _details['timeOfDeletion'] = time_of_deletion

    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.schedule_hsm_cluster_deletion(
        hsm_cluster_id=hsm_cluster_id,
        schedule_hsm_cluster_deletion_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_hsm_cluster') and callable(getattr(client, 'get_hsm_cluster')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds

                click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_hsm_cluster(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.update_audit_logging_destination.command_name', 'update-audit-logging-destination'), help=u"""update bucket details of management audit logs for a HSM cluster resource by hsmClusterId. \n[Command Reference](updateAuditLoggingDestination)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--bucket-name', required=True, help=u"""The bucket name to which audit logs will be stored.""")
@cli_util.option('--namespace', required=True, help=u"""The namespace under bucket to which audit logs will be stored.""")
@cli_util.option('--compartment-id', required=True, help=u"""The compartmentId [OCID] under namespace to which audit logs will be stored.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'key_management', 'class': 'AuditLogging'})
@cli_util.wrap_exceptions
def update_audit_logging_destination(ctx, from_json, hsm_cluster_id, bucket_name, namespace, compartment_id, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}
    _details['bucketName'] = bucket_name
    _details['namespace'] = namespace
    _details['compartmentId'] = compartment_id

    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.update_audit_logging_destination(
        hsm_cluster_id=hsm_cluster_id,
        update_audit_logging_destination_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.update_hsm_cluster.command_name', 'update'), help=u"""Modifies properties of an HSM cluster resource, including `displayName`, `freeformTags` and `definedTags`.

As a provisioning operation, this call is subject to a Key Management limit that applies to the total number of requests across all provisioning write operations. Key Management might throttle this call to reject an otherwise valid request when the total rate of provisioning write operations exceeds 10 requests per second for a given tenancy. \n[Command Reference](updateHsmCluster)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--display-name', help=u"""A user-friendly name for the HSM resource. It does not have to be unique, and it is changeable. Avoid entering confidential information.""")
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True)
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "INITIALIZATION_REQUIRED", "INITIALIZING", "ACTIVATION_REQUIRED", "ACTIVATING", "ACTIVE", "DELETING", "DELETED", "PENDING_DELETION", "SCHEDULING_DELETION", "CANCELLING_DELETION"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state CREATING --wait-for-state CANCELLING_DELETION would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""")
@cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""")
@cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'key_management', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'key_management', 'class': 'dict(str, string)'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'key_management', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'key_management', 'class': 'dict(str, string)'}}, output_type={'module': 'key_management', 'class': 'HsmCluster'})
@cli_util.wrap_exceptions
def update_hsm_cluster(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, hsm_cluster_id, defined_tags, display_name, freeform_tags, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')
    if not force:
        if defined_tags or freeform_tags:
            if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"):
                ctx.abort()

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags)

    if display_name is not None:
        _details['displayName'] = display_name

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags)

    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.update_hsm_cluster(
        hsm_cluster_id=hsm_cluster_id,
        update_hsm_cluster_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_hsm_cluster') and callable(getattr(client, 'get_hsm_cluster')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds

                click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_hsm_cluster(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@hsm_cluster_group.command(name=cli_util.override('kms_hsm_cluster.upload_partition_certificates.command_name', 'upload-partition-certificates'), help=u"""Uploads the partition owner certificates to the HSM Cluster resource. \n[Command Reference](uploadPartitionCertificates)""")
@cli_util.option('--hsm-cluster-id', required=True, help=u"""The OCID of the HSM Cluster. This is a unique identifier assigned to each hsmCluster.""")
@cli_util.option('--partition-certificate', required=True, help=u"""Base64 encoded (StandardCharsets.UTF_8) Partition Certificate, which gets created when the CSR is signed.""")
@cli_util.option('--partition-owner-certificate', required=True, help=u"""Base64 encoded (StandardCharsets.UTF_8) Partition Owner Certificate, which is used to help sign the CSR.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def upload_partition_certificates(ctx, from_json, hsm_cluster_id, partition_certificate, partition_owner_certificate, if_match):

    if isinstance(hsm_cluster_id, six.string_types) and len(hsm_cluster_id.strip()) == 0:
        raise click.UsageError('Parameter --hsm-cluster-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}
    _details['partitionCertificate'] = partition_certificate
    _details['partitionOwnerCertificate'] = partition_owner_certificate

    client = cli_util.build_client('key_management', 'kms_hsm_cluster', ctx)
    result = client.upload_partition_certificates(
        hsm_cluster_id=hsm_cluster_id,
        upload_partition_certificates_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)
