# 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: 20250101

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.distributed_database.src.oci_cli_distributed_database.generated import distributed_database_service_cli


@click.command(cli_util.override('distributed_autonomous_db_service.distributed_autonomous_db_service_root_group.command_name', 'distributed-autonomous-db-service'), cls=CommandGroupWithAlias, help=cli_util.override('distributed_autonomous_db_service.distributed_autonomous_db_service_root_group.help', """Use the Globally Distributed Database service APIs to create and manage the Globally distributed databases."""), short_help=cli_util.override('distributed_autonomous_db_service.distributed_autonomous_db_service_root_group.short_help', """Globally Distributed Database"""))
@cli_util.help_option_group
def distributed_autonomous_db_service_root_group():
    pass


@click.command(cli_util.override('distributed_autonomous_db_service.distributed_autonomous_database_collection_group.command_name', 'distributed-autonomous-database-collection'), cls=CommandGroupWithAlias, help="""Collection of Globally distributed autonomous databases.""")
@cli_util.help_option_group
def distributed_autonomous_database_collection_group():
    pass


@click.command(cli_util.override('distributed_autonomous_db_service.distributed_autonomous_database_group.command_name', 'distributed-autonomous-database'), cls=CommandGroupWithAlias, help="""Globally distributed autonomous database.""")
@cli_util.help_option_group
def distributed_autonomous_database_group():
    pass


@click.command(cli_util.override('distributed_autonomous_db_service.distributed_database_group.command_name', 'distributed-database'), cls=CommandGroupWithAlias, help="""Globally distributed database.""")
@cli_util.help_option_group
def distributed_database_group():
    pass


distributed_database_service_cli.distributed_database_service_group.add_command(distributed_autonomous_db_service_root_group)
distributed_autonomous_db_service_root_group.add_command(distributed_autonomous_database_collection_group)
distributed_autonomous_db_service_root_group.add_command(distributed_autonomous_database_group)
distributed_autonomous_db_service_root_group.add_command(distributed_database_group)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.add_distributed_autonomous_database_gds_control_node.command_name', 'add'), help=u"""Add new Global database services control(GDS CTL) node for the Globally distributed autonomous database. \n[Command Reference](addDistributedAutonomousDatabaseGdsControlNode)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--public-ssh-key', required=True, help=u"""The public sshKey for Global database services control(GDS CTL) node.""")
@cli_util.option('--subnet-id', help=u"""The [OCID] of the subnet on which the Global database services control(GDS CTL) node should be created.""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def add_distributed_autonomous_database_gds_control_node(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, public_ssh_key, subnet_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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['publicSshKey'] = public_ssh_key

    if subnet_id is not None:
        _details['subnetId'] = subnet_id

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.add_distributed_autonomous_database_gds_control_node(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        add_distributed_autonomous_database_gds_control_node_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.change_distributed_autonomous_database_compartment.command_name', 'change-compartment'), help=u"""Move the Globally distributed autonomous database and its dependent resources to the specified compartment. \n[Command Reference](changeDistributedAutonomousDatabaseCompartment)""")
@cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the resource to.""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def change_distributed_autonomous_database_compartment(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, distributed_autonomous_database_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.change_distributed_autonomous_database_compartment(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        change_distributed_autonomous_database_compartment_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.change_distributed_autonomous_db_backup_config.command_name', 'change-distributed-autonomous-db-backup-config'), help=u"""Change the DbBackupConfig for the Globally distributed autonomous database. \n[Command Reference](changeDistributedAutonomousDbBackupConfig)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--db-backup-config', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + 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('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'db-backup-config': {'module': 'distributed_database', 'class': 'DistributedAutonomousDbBackupConfig'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'db-backup-config': {'module': 'distributed_database', 'class': 'DistributedAutonomousDbBackupConfig'}})
@cli_util.wrap_exceptions
def change_distributed_autonomous_db_backup_config(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, db_backup_config, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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['dbBackupConfig'] = cli_util.parse_json_parameter("db_backup_config", db_backup_config)

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.change_distributed_autonomous_db_backup_config(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        change_distributed_autonomous_db_backup_config_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.configure_distributed_autonomous_database_gsm_wallet.command_name', 'configure-distributed-autonomous-database-gsm-wallet'), help=u"""Configure wallets on Global Service Manager(GSM) instances for a Globally distributed autonomous database. \n[Command Reference](configureDistributedAutonomousDatabaseGsmWallet)""")
@cli_util.option('--certificate-id', required=True, help=u"""The [OCID] of the cluster certificate.""")
@cli_util.option('--ca-bundle-id', required=True, help=u"""The [OCID] of the ca bundle id.""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def configure_distributed_autonomous_database_gsm_wallet(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, certificate_id, ca_bundle_id, distributed_autonomous_database_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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['certificateId'] = certificate_id
    _details['caBundleId'] = ca_bundle_id

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.configure_distributed_autonomous_database_gsm_wallet(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        configure_distributed_autonomous_database_gsm_wallet_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.configure_distributed_autonomous_database_gsms.command_name', 'configure-distributed-autonomous-database-gsms'), help=u"""Configure new Global Service Manager(GSM aka shard manager) instances for the Globally distributed autonomous database. \n[Command Reference](configureDistributedAutonomousDatabaseGsms)""")
@cli_util.option('--old-gsm-names', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""Names of old global service manager(GSM) instances corresponding to which new GSM instances need to be configured.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--is-latest-gsm-image', required=True, type=click.BOOL, help=u"""Flag to indicate if new global service manager(GSM) instances shall use latest image or re-use image used by existing GSM instances.""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'old-gsm-names': {'module': 'distributed_database', 'class': 'list[string]'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'old-gsm-names': {'module': 'distributed_database', 'class': 'list[string]'}})
@cli_util.wrap_exceptions
def configure_distributed_autonomous_database_gsms(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, old_gsm_names, is_latest_gsm_image, distributed_autonomous_database_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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['oldGsmNames'] = cli_util.parse_json_parameter("old_gsm_names", old_gsm_names)
    _details['isLatestGsmImage'] = is_latest_gsm_image

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.configure_distributed_autonomous_database_gsms(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        configure_distributed_autonomous_database_gsms_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.configure_distributed_autonomous_database_sharding.command_name', 'configure-distributed-autonomous-database-sharding'), help=u"""Once all components of Globally distributed autonomous database are provisioned, this api shall be invoked to configure sharding on the Globally distributed autonomous database. Note that this 'ConfigureSharding' API also needs to be invoked after successfully adding a new shard to the Globally distributed autonomous database using PATCH api. If this API is not invoked after successfully adding a new shard, then that new shard will not be a participant in sharding topology of the Globally distributed autonomous database. \n[Command Reference](configureDistributedAutonomousDatabaseSharding)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--is-rebalance-required', type=click.BOOL, help=u"""The flag to indicate whether chunks need to be re-balanced. This flag is not applicable for USER-defined sharding type.""")
@cli_util.option('--certificate-id', help=u"""The ID of the cluster certificate.""")
@cli_util.option('--ca-bundle-id', help=u"""The ID of the Ca Bundle.""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def configure_distributed_autonomous_database_sharding(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, is_rebalance_required, certificate_id, ca_bundle_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-id cannot be whitespace or empty string')

    kwargs = {}
    if is_rebalance_required is not None:
        kwargs['is_rebalance_required'] = is_rebalance_required
    if certificate_id is not None:
        kwargs['certificate_id'] = certificate_id
    if ca_bundle_id is not None:
        kwargs['ca_bundle_id'] = ca_bundle_id
    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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.configure_distributed_autonomous_database_sharding(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.create_distributed_autonomous_database.command_name', 'create'), help=u"""Creates a Globally distributed autonomous database. \n[Command Reference](createDistributedAutonomousDatabase)""")
@cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the Globally distributed autonomous database compartment.""")
@cli_util.option('--display-name', required=True, help=u"""The display name of the Globally distributed autonomous database.""")
@cli_util.option('--database-version', required=True, help=u"""Oracle Database version for the shards and catalog used in Globally distributed autonomous database.""")
@cli_util.option('--prefix', required=True, help=u"""Unique name prefix for the Globally distributed autonomous databases. Only alpha-numeric values are allowed. First character has to be a letter followed by any combination of letter and number.""")
@cli_util.option('--private-endpoint-ids', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""The collection of [OCID] of the private endpoint associated with Globally distributed autonomous database.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--sharding-method', required=True, type=custom_types.CliCaseInsensitiveChoice(["USER", "SYSTEM"]), help=u"""Sharding Methods for the Globally distributed autonomous database.""")
@cli_util.option('--db-workload', required=True, type=custom_types.CliCaseInsensitiveChoice(["OLTP", "DW"]), help=u"""Possible workload types. Currently only OLTP workload type is supported.""")
@cli_util.option('--character-set', required=True, help=u"""The character set for the database.""")
@cli_util.option('--ncharacter-set', required=True, help=u"""The national character set for the database.""")
@cli_util.option('--listener-port', required=True, type=click.INT, help=u"""The listener port number for the Globally distributed autonomous database. The listener port number has to be unique for a customer tenancy across all distributed autonomous databases. Same port number should not be re-used for any other distributed autonomous database.""")
@cli_util.option('--ons-port-local', required=True, type=click.INT, help=u"""Ons local port number for Globally distributed autonomous database. The onsPortLocal has to be unique for a customer tenancy across all distributed autonomous databases. Same port number should not be re-used for any other distributed autonomous database.""")
@cli_util.option('--ons-port-remote', required=True, type=click.INT, help=u"""Ons remote port number for Globally distributed autonomous database. The onsPortRemote has to be unique for a customer tenancy across all distributed autonomous databases. Same port number should not be re-used for any other distributed autonomous database.""")
@cli_util.option('--db-deployment-type', required=True, type=custom_types.CliCaseInsensitiveChoice(["ADB_D"]), help=u"""The distributed autonomous database deployment type.""")
@cli_util.option('--shard-details', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""Collection of shards for the Globally distributed autonomous database.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--catalog-details', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""Collection of catalog for the Globally distributed autonomous database.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--chunks', type=click.INT, help=u"""Number of chunks in a shardspace. The value of chunks must be greater than 2 times the size of the largest shardgroup in any shardspace. Chunks is required to be provided for distributed autonomous databases being created with SYSTEM shardingMethod. For USER shardingMethod, chunks should not be set in create payload.""")
@cli_util.option('--listener-port-tls', type=click.INT, help=u"""The TLS listener port number for Globally distributed autonomous database. The TLS listener port number has to be unique for a customer tenancy across all distributed autonomous databases. Same port number should not be re-used for any other distributed autonomous database. The listenerPortTls is mandatory for dedicated infrastructure based distributed autonomous databases.""")
@cli_util.option('--replication-method', type=custom_types.CliCaseInsensitiveChoice(["RAFT", "DG"]), help=u"""The Replication method for Globally distributed autonomous database. Use RAFT for Raft based replication. With RAFT replication, shards cannot have peers details set on them. In case shards need to have peers, please do not set RAFT replicationMethod. For all non RAFT replication cases (with or without peers), please set replicationMethod as DG or do not set any value for replicationMethod.""")
@cli_util.option('--replication-factor', type=click.INT, help=u"""The Replication factor for RAFT replication based Globally distributed autonomous database. Currently supported values are 3, 5 and 7.""")
@cli_util.option('--replication-unit', type=click.INT, help=u"""The replication unit count for RAFT based distributed autonomous database. For RAFT replication based Globally distributed autonomous database, the value should be at least twice the number of shards.""")
@cli_util.option('--db-backup-config', type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. Example: `{\"bar-key\": \"value\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@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. Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'private-endpoint-ids': {'module': 'distributed_database', 'class': 'list[string]'}, 'shard-details': {'module': 'distributed_database', 'class': 'list[CreateDistributedAutonomousDatabaseShardDetails]'}, 'catalog-details': {'module': 'distributed_database', 'class': 'list[CreateDistributedAutonomousDatabaseCatalogDetails]'}, 'db-backup-config': {'module': 'distributed_database', 'class': 'DistributedAutonomousDbBackupConfig'}, 'freeform-tags': {'module': 'distributed_database', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'distributed_database', 'class': 'dict(str, dict(str, object))'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'private-endpoint-ids': {'module': 'distributed_database', 'class': 'list[string]'}, 'shard-details': {'module': 'distributed_database', 'class': 'list[CreateDistributedAutonomousDatabaseShardDetails]'}, 'catalog-details': {'module': 'distributed_database', 'class': 'list[CreateDistributedAutonomousDatabaseCatalogDetails]'}, 'db-backup-config': {'module': 'distributed_database', 'class': 'DistributedAutonomousDbBackupConfig'}, 'freeform-tags': {'module': 'distributed_database', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'distributed_database', 'class': 'dict(str, dict(str, object))'}}, output_type={'module': 'distributed_database', 'class': 'DistributedAutonomousDatabase'})
@cli_util.wrap_exceptions
def create_distributed_autonomous_database(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, display_name, database_version, prefix, private_endpoint_ids, sharding_method, db_workload, character_set, ncharacter_set, listener_port, ons_port_local, ons_port_remote, db_deployment_type, shard_details, catalog_details, chunks, listener_port_tls, replication_method, replication_factor, replication_unit, db_backup_config, freeform_tags, defined_tags):

    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
    _details['databaseVersion'] = database_version
    _details['prefix'] = prefix
    _details['privateEndpointIds'] = cli_util.parse_json_parameter("private_endpoint_ids", private_endpoint_ids)
    _details['shardingMethod'] = sharding_method
    _details['dbWorkload'] = db_workload
    _details['characterSet'] = character_set
    _details['ncharacterSet'] = ncharacter_set
    _details['listenerPort'] = listener_port
    _details['onsPortLocal'] = ons_port_local
    _details['onsPortRemote'] = ons_port_remote
    _details['dbDeploymentType'] = db_deployment_type
    _details['shardDetails'] = cli_util.parse_json_parameter("shard_details", shard_details)
    _details['catalogDetails'] = cli_util.parse_json_parameter("catalog_details", catalog_details)

    if chunks is not None:
        _details['chunks'] = chunks

    if listener_port_tls is not None:
        _details['listenerPortTls'] = listener_port_tls

    if replication_method is not None:
        _details['replicationMethod'] = replication_method

    if replication_factor is not None:
        _details['replicationFactor'] = replication_factor

    if replication_unit is not None:
        _details['replicationUnit'] = replication_unit

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

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

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

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.create_distributed_autonomous_database(
        create_distributed_autonomous_database_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.delete_distributed_autonomous_database.command_name', 'delete'), help=u"""Terminate the given Globally distributed autonomous databases. \n[Command Reference](deleteDistributedAutonomousDatabase)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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.confirm_delete_option
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def delete_distributed_autonomous_database(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.delete_distributed_autonomous_database(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request entered the specified state. Please retrieve the work request to find its current state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.download_distributed_autonomous_database_gsm_certificate_signing_request.command_name', 'download-distributed-autonomous-database-gsm-certificate-signing-request'), help=u"""Generate the common certificate signing request for GSMs. Download the <globalautonomousdb-prefix>.csr file from API response. Users can use this .csr file to generate the CA signed certificate, and as a next step use 'uploadSignedCertificateAndGenerateWallet' API to upload the CA signed certificate to GSM, and generate wallets for the GSM instances of the Globally distributed autonomous database. \n[Command Reference](downloadDistributedAutonomousDatabaseGsmCertificateSigningRequest)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--file', type=click.File(mode='wb'), required=True, help="The name of the file that will receive the response data, or '-' to write to STDOUT.")
@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_distributed_autonomous_database_gsm_certificate_signing_request(ctx, from_json, file, distributed_autonomous_database_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.download_distributed_autonomous_database_gsm_certificate_signing_request(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )

    # If outputting to stdout we don't want to print a progress bar because it will get mixed up with the output
    # Also we need a non-zero Content-Length in order to display a meaningful progress bar
    bar = None
    if hasattr(file, 'name') and file.name != '<stdout>' and 'Content-Length' in result.headers:
        content_length = int(result.headers['Content-Length'])
        if content_length > 0:
            bar = click.progressbar(length=content_length, label='Downloading file')

    try:
        if bar:
            bar.__enter__()

        # TODO: Make the download size a configurable option
        # use decode_content=True to automatically unzip service responses (this should be overridden for object storage)
        for chunk in result.data.raw.stream(cli_constants.MEBIBYTE, decode_content=True):
            if bar:
                bar.update(len(chunk))
            file.write(chunk)
    finally:
        if bar:
            bar.render_finish()
        file.close()


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.generate_distributed_autonomous_database_gsm_certificate_signing_request.command_name', 'generate-distributed-autonomous-database-gsm-certificate-signing-request'), help=u"""Generate the certificate signing request for GSM instances of the Globally distributed autonomous database. Once certificate signing request is generated, then customers can download the certificate signing request using 'downloadGsmCertificateSigningRequest' api call. \n[Command Reference](generateDistributedAutonomousDatabaseGsmCertificateSigningRequest)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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('--ca-bundle-id', help=u"""The ID of the Ca Bundle.""")
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def generate_distributed_autonomous_database_gsm_certificate_signing_request(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, if_match, ca_bundle_id):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    if ca_bundle_id is not None:
        kwargs['ca_bundle_id'] = ca_bundle_id
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.generate_distributed_autonomous_database_gsm_certificate_signing_request(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.generate_distributed_autonomous_database_wallet.command_name', 'generate-distributed-autonomous-database-wallet'), help=u"""Generate the wallet associated with Globally distributed autonomous database. \n[Command Reference](generateDistributedAutonomousDatabaseWallet)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--password', required=True, help=u"""The password to encrypt the keys inside the wallet. The password must be at least 8 characters long and must include at least 1 letter and either 1 numeric character or 1 special character.""")
@cli_util.option('--file', type=click.File(mode='wb'), required=True, help="The name of the file that will receive the response data, or '-' to write to STDOUT.")
@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 generate_distributed_autonomous_database_wallet(ctx, from_json, file, distributed_autonomous_database_id, password, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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['password'] = password

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.generate_distributed_autonomous_database_wallet(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        generate_distributed_autonomous_database_wallet_details=_details,
        **kwargs
    )

    # If outputting to stdout we don't want to print a progress bar because it will get mixed up with the output
    # Also we need a non-zero Content-Length in order to display a meaningful progress bar
    bar = None
    if hasattr(file, 'name') and file.name != '<stdout>' and 'Content-Length' in result.headers:
        content_length = int(result.headers['Content-Length'])
        if content_length > 0:
            bar = click.progressbar(length=content_length, label='Downloading file')

    try:
        if bar:
            bar.__enter__()

        # TODO: Make the download size a configurable option
        # use decode_content=True to automatically unzip service responses (this should be overridden for object storage)
        for chunk in result.data.raw.stream(cli_constants.MEBIBYTE, decode_content=True):
            if bar:
                bar.update(len(chunk))
            file.write(chunk)
    finally:
        if bar:
            bar.render_finish()
        file.close()


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.get_distributed_autonomous_database.command_name', 'get'), help=u"""Gets the details of the Globally distributed autonomous database identified by given id. \n[Command Reference](getDistributedAutonomousDatabase)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--metadata', help=u"""Comma separated names of argument corresponding to which metadata need to be retrived.""")
@cli_util.option('--if-none-match', help=u"""For conditional requests. In the GET call for a resource, set the `If-None-Match` header to the value of the ETag from a previous GET (or POST or PUT) response for that resource. The server will return with either a 304 Not Modified response if the resource has not changed, or a 200 OK response with the updated representation.""")
@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': 'distributed_database', 'class': 'DistributedAutonomousDatabase'})
@cli_util.wrap_exceptions
def get_distributed_autonomous_database(ctx, from_json, distributed_autonomous_database_id, metadata, if_none_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-id cannot be whitespace or empty string')

    kwargs = {}
    if metadata is not None:
        kwargs['metadata'] = metadata
    if if_none_match is not None:
        kwargs['if_none_match'] = if_none_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.get_distributed_autonomous_database(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@distributed_database_group.command(name=cli_util.override('distributed_autonomous_db_service.get_distributed_autonomous_database_raft_metric.command_name', 'get-distributed-autonomous-database-raft-metric'), help=u"""Operation to retrieve RAFT metrics for the Globally distributed autonomous database. If the Globally distributed autonomous database is not RAFT based then empty response is returned from the API. \n[Command Reference](getDistributedAutonomousDatabaseRaftMetric)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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': 'distributed_database', 'class': 'DistributedAutonomousDatabaseRaftMetric'})
@cli_util.wrap_exceptions
def get_distributed_autonomous_database_raft_metric(ctx, from_json, distributed_autonomous_database_id):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.get_distributed_autonomous_database_raft_metric(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_collection_group.command(name=cli_util.override('distributed_autonomous_db_service.list_distributed_autonomous_databases.command_name', 'list-distributed-autonomous-databases'), help=u"""List of Globally distributed autonomous databases. \n[Command Reference](listDistributedAutonomousDatabases)""")
@cli_util.option('--compartment-id', required=True, help=u"""The ID of the compartment in which to list resources.""")
@cli_util.option('--private-endpoint-id', help=u"""A filter to return only resources that are associated with the given privateEndpointId.""")
@cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["ACTIVE", "FAILED", "NEEDS_ATTENTION", "INACTIVE", "DELETING", "DELETED", "UPDATING", "CREATING"]), help=u"""A filter to return only resources their lifecycleState matches the given lifecycleState.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of items to return.""")
@cli_util.option('--page', help=u"""A token representing the position at which to start retrieving results. This must come from the `opc-next-page` header field of a previous response.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either 'ASC' or 'DESC'.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["timeCreated", "timeUpdated"]), help=u"""The field to sort by. Only one sort order may be provided. Default order for timeCreated is descending. Default order for displayName is ascending.""")
@cli_util.option('--display-name', help=u"""A filter to return only Globally distributed autonomous databases that match the entire name given. The match is not case sensitive.""")
@cli_util.option('--db-deployment-type', type=custom_types.CliCaseInsensitiveChoice(["ADB_D"]), help=u"""A filter to return only resources their dbDeploymentType matches the given dbDeploymentType.""")
@cli_util.option('--metadata', help=u"""Comma separated names of argument corresponding to which metadata need to be retrived.""")
@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': 'distributed_database', 'class': 'DistributedAutonomousDatabaseCollection'})
@cli_util.wrap_exceptions
def list_distributed_autonomous_databases(ctx, from_json, all_pages, page_size, compartment_id, private_endpoint_id, lifecycle_state, limit, page, sort_order, sort_by, display_name, db_deployment_type, metadata):

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

    kwargs = {}
    if private_endpoint_id is not None:
        kwargs['private_endpoint_id'] = private_endpoint_id
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    if limit is not None:
        kwargs['limit'] = limit
    if page is not None:
        kwargs['page'] = page
    if sort_order is not None:
        kwargs['sort_order'] = sort_order
    if sort_by is not None:
        kwargs['sort_by'] = sort_by
    if display_name is not None:
        kwargs['display_name'] = display_name
    if db_deployment_type is not None:
        kwargs['db_deployment_type'] = db_deployment_type
    if metadata is not None:
        kwargs['metadata'] = metadata
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.move_distributed_autonomous_database_replication_unit.command_name', 'move-distributed-autonomous-database-replication-unit'), help=u"""Move the replication units for RAFT based globally distributed autonomous database from source shard to destination shard. \n[Command Reference](moveDistributedAutonomousDatabaseReplicationUnit)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--source-shard-name', required=True, help=u"""The name of the source shard from which to move the chunks out to other shards.""")
@cli_util.option('--destination-shard-name', help=u"""The name of the destination shard to which the chunks moved out from source shard should be relocate to.""")
@cli_util.option('--replication-units', type=custom_types.CLI_COMPLEX_TYPE, help=u"""For RAFT databases please provide replication unit numbers to be moved from source shard to destination shard.""" + 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('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'replication-units': {'module': 'distributed_database', 'class': 'list[integer]'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'replication-units': {'module': 'distributed_database', 'class': 'list[integer]'}})
@cli_util.wrap_exceptions
def move_distributed_autonomous_database_replication_unit(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, source_shard_name, destination_shard_name, replication_units, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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['sourceShardName'] = source_shard_name

    if destination_shard_name is not None:
        _details['destinationShardName'] = destination_shard_name

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

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.move_distributed_autonomous_database_replication_unit(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        move_distributed_autonomous_database_replication_unit_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.patch_distributed_autonomous_database.command_name', 'patch'), help=u"""Patch operation to add, remove or update shards to the Globally distributed autonomous database topology. In single patch operation, multiple shards can be either added, or removed or updated. Combination of inserts, update and remove in single operation is not allowed. \n[Command Reference](patchDistributedAutonomousDatabase)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--items', type=custom_types.CLI_COMPLEX_TYPE, help=u"""List of patch instructions.

This option is a JSON list with items of type PatchInstruction.  For documentation on PatchInstruction please see our API reference: https://docs.oracle.com/en-us/iaas/api/#/en/distributedautonomousdbservice/20250101/datatypes/PatchInstruction.""" + 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('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'items': {'module': 'distributed_database', 'class': 'list[PatchInstruction]'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'items': {'module': 'distributed_database', 'class': 'list[PatchInstruction]'}})
@cli_util.wrap_exceptions
def patch_distributed_autonomous_database(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, items, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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 items is not None:
        _details['items'] = cli_util.parse_json_parameter("items", items)

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.patch_distributed_autonomous_database(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        patch_distributed_autonomous_database_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.recreate_failed_distributed_autonomous_database_resource.command_name', 'recreate-failed-distributed-autonomous-database-resource'), help=u"""Recreate the failed resource for the Globally Distributed Autonomous Database. \n[Command Reference](recreateFailedDistributedAutonomousDatabaseResource)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--resource-name', required=True, help=u"""Specify the name of Shard, Catalog or GSM.""")
@cli_util.option('--shard-group', help=u"""The shardGroup name example Shardgroupa, Shardgroupb.""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def recreate_failed_distributed_autonomous_database_resource(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, resource_name, shard_group, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-id cannot be whitespace or empty string')

    kwargs = {}
    if shard_group is not None:
        kwargs['shard_group'] = shard_group
    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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.recreate_failed_distributed_autonomous_database_resource(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        resource_name=resource_name,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.rotate_distributed_autonomous_database_passwords.command_name', 'rotate-distributed-autonomous-database-passwords'), help=u"""Rotate the gsmuser and gsmcatuser passwords for shards and catalog of the Globally distributed autonomous database. This operation will also remove GdsCtlNodes if present. \n[Command Reference](rotateDistributedAutonomousDatabasePasswords)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def rotate_distributed_autonomous_database_passwords(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.rotate_distributed_autonomous_database_passwords(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.start_distributed_autonomous_database.command_name', 'start'), help=u"""Start the shards, catalog and GSMs of Globally distributed autonomous database. \n[Command Reference](startDistributedAutonomousDatabase)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def start_distributed_autonomous_database(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.start_distributed_autonomous_database(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.stop_distributed_autonomous_database.command_name', 'stop'), help=u"""Stop the shards, catalog and GSM instances for the Globally distributed autonomous database. \n[Command Reference](stopDistributedAutonomousDatabase)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def stop_distributed_autonomous_database(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.stop_distributed_autonomous_database(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.update_distributed_autonomous_database.command_name', 'update'), help=u"""Updates the configuration of the Globally distributed autonomous database. \n[Command Reference](updateDistributedAutonomousDatabase)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--display-name', help=u"""Display name of the Globally distributed autonomous database.""")
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. Example: `{\"bar-key\": \"value\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@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. Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}`""" + 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(["ACTIVE", "FAILED", "NEEDS_ATTENTION", "INACTIVE", "DELETING", "DELETED", "UPDATING", "CREATING"]), 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 ACTIVE --wait-for-state CREATING 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({'freeform-tags': {'module': 'distributed_database', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'distributed_database', 'class': 'dict(str, dict(str, object))'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'freeform-tags': {'module': 'distributed_database', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'distributed_database', 'class': 'dict(str, dict(str, object))'}}, output_type={'module': 'distributed_database', 'class': 'DistributedAutonomousDatabase'})
@cli_util.wrap_exceptions
def update_distributed_autonomous_database(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, display_name, freeform_tags, defined_tags, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-id cannot be whitespace or empty string')
    if not force:
        if freeform_tags or defined_tags:
            if not click.confirm("WARNING: Updates to freeform-tags and defined-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 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)

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

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.update_distributed_autonomous_database(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        update_distributed_autonomous_database_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_distributed_autonomous_database') and callable(getattr(client, 'get_distributed_autonomous_database')):
            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_distributed_autonomous_database(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)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.upload_distributed_autonomous_database_signed_certificate_and_generate_wallet.command_name', 'upload-distributed-autonomous-database-signed-certificate-and-generate-wallet'), help=u"""Upload the CA signed certificate to the GSM instances and generate wallets for GSM instances of the Globally distributed autonomous database. Customer shall provide the CA signed certificate key details by adding the certificate in request body. \n[Command Reference](uploadDistributedAutonomousDatabaseSignedCertificateAndGenerateWallet)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--ca-signed-certificate', required=True, help=u"""The CA signed certificate key.""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def upload_distributed_autonomous_database_signed_certificate_and_generate_wallet(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, ca_signed_certificate, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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['caSignedCertificate'] = ca_signed_certificate

    client = cli_util.build_client('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.upload_distributed_autonomous_database_signed_certificate_and_generate_wallet(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        upload_distributed_autonomous_database_signed_certificate_and_generate_wallet_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.validate_distributed_autonomous_database_ca_bundle.command_name', 'validate-distributed-autonomous-database-ca-bundle'), help=u"""Validate the CA Bundles consistency of the globally distributed autonomous database. \n[Command Reference](validateDistributedAutonomousDatabaseCaBundle)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def validate_distributed_autonomous_database_ca_bundle(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.validate_distributed_autonomous_database_ca_bundle(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@distributed_autonomous_database_group.command(name=cli_util.override('distributed_autonomous_db_service.validate_distributed_autonomous_database_network.command_name', 'validate-distributed-autonomous-database-network'), help=u"""Validate the network connectivity between components of the globally distributed autonomous database. \n[Command Reference](validateDistributedAutonomousDatabaseNetwork)""")
@cli_util.option('--distributed-autonomous-database-id', required=True, help=u"""Globally distributed autonomous database identifier""")
@cli_util.option('--is-surrogate', type=click.BOOL, help=u"""Determines the surrogates check. Default is true.""")
@cli_util.option('--resource-name', help=u"""Specify the name of shard or catalog.""")
@cli_util.option('--shard-group', help=u"""The shardGroup name example Shardgroupa, Shardgroupb.""")
@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(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state NEEDS_ATTENTION 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 work request to reach the 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 work request has reached the 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={})
@cli_util.wrap_exceptions
def validate_distributed_autonomous_database_network(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, distributed_autonomous_database_id, is_surrogate, resource_name, shard_group, if_match):

    if isinstance(distributed_autonomous_database_id, six.string_types) and len(distributed_autonomous_database_id.strip()) == 0:
        raise click.UsageError('Parameter --distributed-autonomous-database-id cannot be whitespace or empty string')

    kwargs = {}
    if is_surrogate is not None:
        kwargs['is_surrogate'] = is_surrogate
    if resource_name is not None:
        kwargs['resource_name'] = resource_name
    if shard_group is not None:
        kwargs['shard_group'] = shard_group
    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('distributed_database', 'distributed_autonomous_db_service', ctx)
    result = client.validate_distributed_autonomous_database_network(
        distributed_autonomous_database_id=distributed_autonomous_database_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_work_request')):
            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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', 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 work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)
