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

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.os_management_hub.src.oci_cli_os_management_hub.generated import os_management_hub_service_cli


@click.command(cli_util.override('dynamic_set.dynamic_set_root_group.command_name', 'dynamic-set'), cls=CommandGroupWithAlias, help=cli_util.override('dynamic_set.dynamic_set_root_group.help', """Use the OS Management Hub API to manage and monitor updates and patches for instances in OCI, your private data center, or 3rd-party clouds.
For more information, see [Overview of OS Management Hub]."""), short_help=cli_util.override('dynamic_set.dynamic_set_root_group.short_help', """OS Management Hub API"""))
@cli_util.help_option_group
def dynamic_set_root_group():
    pass


@click.command(cli_util.override('dynamic_set.dynamic_set_group.command_name', 'dynamic-set'), cls=CommandGroupWithAlias, help="""An object that defines the dynamic set.""")
@cli_util.help_option_group
def dynamic_set_group():
    pass


os_management_hub_service_cli.os_management_hub_service_group.add_command(dynamic_set_root_group)
dynamic_set_root_group.add_command(dynamic_set_group)


@dynamic_set_group.command(name=cli_util.override('dynamic_set.change_dynamic_set_compartment.command_name', 'change-compartment'), help=u"""Move the specified Dynamic Set to a different compartment \n[Command Reference](changeDynamicSetCompartment)""")
@cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the group to.""")
@cli_util.option('--dynamic-set-id', required=True, help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def change_dynamic_set_compartment(ctx, from_json, compartment_id, dynamic_set_id, if_match):

    if isinstance(dynamic_set_id, six.string_types) and len(dynamic_set_id.strip()) == 0:
        raise click.UsageError('Parameter --dynamic-set-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('os_management_hub', 'dynamic_set', ctx)
    result = client.change_dynamic_set_compartment(
        dynamic_set_id=dynamic_set_id,
        change_dynamic_set_compartment_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@dynamic_set_group.command(name=cli_util.override('dynamic_set.create_dynamic_set.command_name', 'create'), help=u"""Creates a new dynamic set. \n[Command Reference](createDynamicSet)""")
@cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment that contains the dynamic set.""")
@cli_util.option('--target-compartments', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of compartment details.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--match-type', required=True, type=custom_types.CliCaseInsensitiveChoice(["ANY", "ALL"]), help=u"""Include either any or all attributes.""")
@cli_util.option('--matching-rule', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--display-name', help=u"""User-friendly name for the dynamic set.""")
@cli_util.option('--description', help=u"""User-specified description for the dynamic set.""")
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "UPDATING", "ACTIVE", "DELETING", "DELETED", "FAILED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state CREATING --wait-for-state FAILED 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({'target-compartments': {'module': 'os_management_hub', 'class': 'list[TargetCompartmentDetails]'}, 'matching-rule': {'module': 'os_management_hub', 'class': 'MatchingRule'}, 'freeform-tags': {'module': 'os_management_hub', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'os_management_hub', '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={'target-compartments': {'module': 'os_management_hub', 'class': 'list[TargetCompartmentDetails]'}, 'matching-rule': {'module': 'os_management_hub', 'class': 'MatchingRule'}, 'freeform-tags': {'module': 'os_management_hub', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'os_management_hub', 'class': 'dict(str, dict(str, object))'}}, output_type={'module': 'os_management_hub', 'class': 'DynamicSet'})
@cli_util.wrap_exceptions
def create_dynamic_set(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, target_compartments, match_type, matching_rule, display_name, description, 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['targetCompartments'] = cli_util.parse_json_parameter("target_compartments", target_compartments)
    _details['matchType'] = match_type
    _details['matchingRule'] = cli_util.parse_json_parameter("matching_rule", matching_rule)

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

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

    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('os_management_hub', 'dynamic_set', ctx)
    result = client.create_dynamic_set(
        create_dynamic_set_details=_details,
        **kwargs
    )
    if wait_for_state:

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


@dynamic_set_group.command(name=cli_util.override('dynamic_set.delete_dynamic_set.command_name', 'delete'), help=u"""Deletes the specific dynamic set \n[Command Reference](deleteDynamicSet)""")
@cli_util.option('--dynamic-set-id', required=True, help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@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(["CREATING", "UPDATING", "ACTIVE", "DELETING", "DELETED", "FAILED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state CREATING --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""")
@cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""")
@cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def delete_dynamic_set(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, dynamic_set_id, if_match):

    if isinstance(dynamic_set_id, six.string_types) and len(dynamic_set_id.strip()) == 0:
        raise click.UsageError('Parameter --dynamic-set-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('os_management_hub', 'dynamic_set', ctx)
    result = client.delete_dynamic_set(
        dynamic_set_id=dynamic_set_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_dynamic_set') and callable(getattr(client, 'get_dynamic_set')):
            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)
                oci.wait_until(client, client.get_dynamic_set(dynamic_set_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs)
            except oci.exceptions.ServiceError as e:
                # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the
                # outcome of a delete operation it is possible that the resource is already gone and so the initial service call
                # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising
                # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument
                # succeed_on_not_found=True to the waiter).
                #
                # Any non-404 should still result in the exception being thrown.
                if e.status == 404:
                    pass
                else:
                    raise
            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. Please retrieve the resource 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 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)


@dynamic_set_group.command(name=cli_util.override('dynamic_set.get_dynamic_set.command_name', 'get'), help=u"""Gets information about the specified dynamic set. \n[Command Reference](getDynamicSet)""")
@cli_util.option('--dynamic-set-id', required=True, help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@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': 'os_management_hub', 'class': 'DynamicSet'})
@cli_util.wrap_exceptions
def get_dynamic_set(ctx, from_json, dynamic_set_id):

    if isinstance(dynamic_set_id, six.string_types) and len(dynamic_set_id.strip()) == 0:
        raise click.UsageError('Parameter --dynamic-set-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('os_management_hub', 'dynamic_set', ctx)
    result = client.get_dynamic_set(
        dynamic_set_id=dynamic_set_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@dynamic_set_group.command(name=cli_util.override('dynamic_set.install_packages_on_dynamic_set.command_name', 'install-packages'), help=u"""Installs specified software packages on all managed instances in the dynamic set. \n[Command Reference](installPackagesOnDynamicSet)""")
@cli_util.option('--dynamic-set-id', required=True, help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@cli_util.option('--package-names', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of package names.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--managed-instances', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of managed instance OCIDs to be attached/detached.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--work-request-details', 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(["WAITING", "ACCEPTED", "IN_PROGRESS", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "SKIPPED"]), 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 WAITING --wait-for-state SKIPPED 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({'managed-instances': {'module': 'os_management_hub', 'class': 'list[string]'}, 'package-names': {'module': 'os_management_hub', 'class': 'list[string]'}, 'work-request-details': {'module': 'os_management_hub', 'class': 'WorkRequestDetails'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'managed-instances': {'module': 'os_management_hub', 'class': 'list[string]'}, 'package-names': {'module': 'os_management_hub', 'class': 'list[string]'}, 'work-request-details': {'module': 'os_management_hub', 'class': 'WorkRequestDetails'}})
@cli_util.wrap_exceptions
def install_packages_on_dynamic_set(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, dynamic_set_id, package_names, managed_instances, work_request_details, if_match):

    if isinstance(dynamic_set_id, six.string_types) and len(dynamic_set_id.strip()) == 0:
        raise click.UsageError('Parameter --dynamic-set-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['packageNames'] = cli_util.parse_json_parameter("package_names", package_names)

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

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

    client = cli_util.build_client('os_management_hub', 'dynamic_set', ctx)
    result = client.install_packages_on_dynamic_set(
        dynamic_set_id=dynamic_set_id,
        install_packages_on_dynamic_set_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)


@dynamic_set_group.command(name=cli_util.override('dynamic_set.list_dynamic_sets.command_name', 'list'), help=u"""Lists dynamic sets that match the specified compartment or dynamic set OCID. Filter the list against a variety of criteria including but not limited to its name, status, architecture, and OS version. \n[Command Reference](listDynamicSets)""")
@cli_util.option('--compartment-id', help=u"""The OCID of the compartment that contains the resources to list. This filter returns only resources contained within the specified compartment.""")
@cli_util.option('--display-name-contains', help=u"""A filter to return resources that may partially match the given display name.""")
@cli_util.option('--display-name', help=u"""A filter to return resources that match the given user-friendly name.""")
@cli_util.option('--dynamic-set-id', help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination].

Example: `50`""")
@cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].

Example: `3`""")
@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", "displayName"]), 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('--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': 'os_management_hub', 'class': 'DynamicSetCollection'})
@cli_util.wrap_exceptions
def list_dynamic_sets(ctx, from_json, all_pages, page_size, compartment_id, display_name_contains, display_name, dynamic_set_id, limit, page, sort_order, sort_by):

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

    kwargs = {}
    if compartment_id is not None:
        kwargs['compartment_id'] = compartment_id
    if display_name_contains is not None:
        kwargs['display_name_contains'] = display_name_contains
    if display_name is not None:
        kwargs['display_name'] = display_name
    if dynamic_set_id is not None:
        kwargs['dynamic_set_id'] = dynamic_set_id
    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
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('os_management_hub', 'dynamic_set', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@dynamic_set_group.command(name=cli_util.override('dynamic_set.list_managed_instances_in_dynamic_set.command_name', 'list-managed-instances-in'), help=u"""Retrieves a list of managed instances associated with a specified dynamic set. \n[Command Reference](listManagedInstancesInDynamicSet)""")
@cli_util.option('--dynamic-set-id', required=True, help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@cli_util.option('--compartment-id', help=u"""The OCID of the compartment that contains the resources to list. This filter returns only resources contained within the specified compartment.""")
@cli_util.option('--compartment-id-in-subtree', type=click.BOOL, help=u"""Indicates whether to include subcompartments in the returned results. Default is false.""")
@cli_util.option('--display-name-contains', help=u"""A filter to return resources that may partially match the given display name.""")
@cli_util.option('--display-name', help=u"""A filter to return resources that match the given user-friendly name.""")
@cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination].

Example: `50`""")
@cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].

Example: `3`""")
@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", "displayName"]), 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('--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': 'os_management_hub', 'class': 'ManagedInstanceCollection'})
@cli_util.wrap_exceptions
def list_managed_instances_in_dynamic_set(ctx, from_json, all_pages, page_size, dynamic_set_id, compartment_id, compartment_id_in_subtree, display_name_contains, display_name, limit, page, sort_order, sort_by):

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

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

    kwargs = {}
    if compartment_id is not None:
        kwargs['compartment_id'] = compartment_id
    if compartment_id_in_subtree is not None:
        kwargs['compartment_id_in_subtree'] = compartment_id_in_subtree
    if display_name_contains is not None:
        kwargs['display_name_contains'] = display_name_contains
    if display_name is not None:
        kwargs['display_name'] = display_name
    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
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('os_management_hub', 'dynamic_set', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@dynamic_set_group.command(name=cli_util.override('dynamic_set.preview_managed_instances.command_name', 'preview-managed-instances'), help=u"""Preview a dynamic set \n[Command Reference](previewManagedInstances)""")
@cli_util.option('--target-compartments', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of compartment details.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--match-type', required=True, type=custom_types.CliCaseInsensitiveChoice(["ANY", "ALL"]), help=u"""Include either any or all attributes.""")
@cli_util.option('--matching-rule', required=True, 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"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--compartment-id', help=u"""The OCID of the compartment that contains the resources to list. This filter returns only resources contained within the specified compartment.""")
@cli_util.option('--compartment-id-in-subtree', type=click.BOOL, help=u"""Indicates whether to include subcompartments in the returned results. Default is false.""")
@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('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination].

Example: `50`""")
@cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].

Example: `3`""")
@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", "displayName"]), 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 resources that match the given user-friendly name.""")
@cli_util.option('--display-name-contains', help=u"""A filter to return resources that may partially match the given display name.""")
@json_skeleton_utils.get_cli_json_input_option({'target-compartments': {'module': 'os_management_hub', 'class': 'list[TargetCompartmentDetails]'}, 'matching-rule': {'module': 'os_management_hub', 'class': 'MatchingRule'}, 'freeform-tags': {'module': 'os_management_hub', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'os_management_hub', '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={'target-compartments': {'module': 'os_management_hub', 'class': 'list[TargetCompartmentDetails]'}, 'matching-rule': {'module': 'os_management_hub', 'class': 'MatchingRule'}, 'freeform-tags': {'module': 'os_management_hub', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'os_management_hub', 'class': 'dict(str, dict(str, object))'}}, output_type={'module': 'os_management_hub', 'class': 'ManagedInstanceCollection'})
@cli_util.wrap_exceptions
def preview_managed_instances(ctx, from_json, target_compartments, match_type, matching_rule, freeform_tags, defined_tags, compartment_id, compartment_id_in_subtree, if_match, limit, page, sort_order, sort_by, display_name, display_name_contains):

    kwargs = {}
    if compartment_id is not None:
        kwargs['compartment_id'] = compartment_id
    if compartment_id_in_subtree is not None:
        kwargs['compartment_id_in_subtree'] = compartment_id_in_subtree
    if if_match is not None:
        kwargs['if_match'] = if_match
    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 display_name_contains is not None:
        kwargs['display_name_contains'] = display_name_contains
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}
    _details['targetCompartments'] = cli_util.parse_json_parameter("target_compartments", target_compartments)
    _details['matchType'] = match_type
    _details['matchingRule'] = cli_util.parse_json_parameter("matching_rule", matching_rule)

    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('os_management_hub', 'dynamic_set', ctx)
    result = client.preview_managed_instances(
        preview_managed_instances_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@dynamic_set_group.command(name=cli_util.override('dynamic_set.reboot_dynamic_set.command_name', 'reboot'), help=u"""Initiates a reboot of all managed instances within the specified dynamic set. \n[Command Reference](rebootDynamicSet)""")
@cli_util.option('--dynamic-set-id', required=True, help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@cli_util.option('--reboot-timeout-in-mins', type=click.INT, help=u"""The number of minutes the service waits for the reboot to complete. If the instances in the group don't reboot within this time, the reboot job status is set to failed.""")
@cli_util.option('--managed-instances', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of managed instance OCIDs to be attached/detached.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--work-request-details', 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(["WAITING", "ACCEPTED", "IN_PROGRESS", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "SKIPPED"]), 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 WAITING --wait-for-state SKIPPED 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({'managed-instances': {'module': 'os_management_hub', 'class': 'list[string]'}, 'work-request-details': {'module': 'os_management_hub', 'class': 'WorkRequestDetails'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'managed-instances': {'module': 'os_management_hub', 'class': 'list[string]'}, 'work-request-details': {'module': 'os_management_hub', 'class': 'WorkRequestDetails'}})
@cli_util.wrap_exceptions
def reboot_dynamic_set(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, dynamic_set_id, reboot_timeout_in_mins, managed_instances, work_request_details, if_match):

    if isinstance(dynamic_set_id, six.string_types) and len(dynamic_set_id.strip()) == 0:
        raise click.UsageError('Parameter --dynamic-set-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 reboot_timeout_in_mins is not None:
        _details['rebootTimeoutInMins'] = reboot_timeout_in_mins

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

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

    client = cli_util.build_client('os_management_hub', 'dynamic_set', ctx)
    result = client.reboot_dynamic_set(
        dynamic_set_id=dynamic_set_id,
        reboot_dynamic_set_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)


@dynamic_set_group.command(name=cli_util.override('dynamic_set.remove_packages_from_dynamic_set.command_name', 'remove'), help=u"""Removes specified software packages from all managed instances in the dynamic set. \n[Command Reference](removePackagesFromDynamicSet)""")
@cli_util.option('--dynamic-set-id', required=True, help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@cli_util.option('--package-names', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of package names.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--managed-instances', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of managed instance OCIDs to be attached/detached.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--work-request-details', 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(["WAITING", "ACCEPTED", "IN_PROGRESS", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "SKIPPED"]), 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 WAITING --wait-for-state SKIPPED 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({'managed-instances': {'module': 'os_management_hub', 'class': 'list[string]'}, 'package-names': {'module': 'os_management_hub', 'class': 'list[string]'}, 'work-request-details': {'module': 'os_management_hub', 'class': 'WorkRequestDetails'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'managed-instances': {'module': 'os_management_hub', 'class': 'list[string]'}, 'package-names': {'module': 'os_management_hub', 'class': 'list[string]'}, 'work-request-details': {'module': 'os_management_hub', 'class': 'WorkRequestDetails'}})
@cli_util.wrap_exceptions
def remove_packages_from_dynamic_set(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, dynamic_set_id, package_names, managed_instances, work_request_details, if_match):

    if isinstance(dynamic_set_id, six.string_types) and len(dynamic_set_id.strip()) == 0:
        raise click.UsageError('Parameter --dynamic-set-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['packageNames'] = cli_util.parse_json_parameter("package_names", package_names)

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

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

    client = cli_util.build_client('os_management_hub', 'dynamic_set', ctx)
    result = client.remove_packages_from_dynamic_set(
        dynamic_set_id=dynamic_set_id,
        remove_packages_from_dynamic_set_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)


@dynamic_set_group.command(name=cli_util.override('dynamic_set.update_dynamic_set.command_name', 'update'), help=u"""Updates the specified dynamic set. \n[Command Reference](updateDynamicSet)""")
@cli_util.option('--dynamic-set-id', required=True, help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@cli_util.option('--display-name', help=u"""User-friendly name for the dynamic set.""")
@cli_util.option('--description', help=u"""User-specified description of the dynamic set. Avoid entering confidential information.""")
@cli_util.option('--target-compartments', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of compartment details.

This option is a JSON list with items of type TargetCompartmentDetails.  For documentation on TargetCompartmentDetails please see our API reference: https://docs.oracle.com/en-us/iaas/api/#/en/dynamicset/20220901/datatypes/TargetCompartmentDetails.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--match-type', type=custom_types.CliCaseInsensitiveChoice(["ANY", "ALL"]), help=u"""Include either any or all attributes.""")
@cli_util.option('--matching-rule', 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"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True)
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "UPDATING", "ACTIVE", "DELETING", "DELETED", "FAILED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state CREATING --wait-for-state FAILED 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({'target-compartments': {'module': 'os_management_hub', 'class': 'list[TargetCompartmentDetails]'}, 'matching-rule': {'module': 'os_management_hub', 'class': 'MatchingRule'}, 'freeform-tags': {'module': 'os_management_hub', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'os_management_hub', '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={'target-compartments': {'module': 'os_management_hub', 'class': 'list[TargetCompartmentDetails]'}, 'matching-rule': {'module': 'os_management_hub', 'class': 'MatchingRule'}, 'freeform-tags': {'module': 'os_management_hub', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'os_management_hub', 'class': 'dict(str, dict(str, object))'}}, output_type={'module': 'os_management_hub', 'class': 'DynamicSet'})
@cli_util.wrap_exceptions
def update_dynamic_set(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, dynamic_set_id, display_name, description, target_compartments, match_type, matching_rule, freeform_tags, defined_tags, if_match):

    if isinstance(dynamic_set_id, six.string_types) and len(dynamic_set_id.strip()) == 0:
        raise click.UsageError('Parameter --dynamic-set-id cannot be whitespace or empty string')
    if not force:
        if target_compartments or matching_rule or freeform_tags or defined_tags:
            if not click.confirm("WARNING: Updates to target-compartments and matching-rule and 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 description is not None:
        _details['description'] = description

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

    if match_type is not None:
        _details['matchType'] = match_type

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

    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('os_management_hub', 'dynamic_set', ctx)
    result = client.update_dynamic_set(
        dynamic_set_id=dynamic_set_id,
        update_dynamic_set_details=_details,
        **kwargs
    )
    if wait_for_state:

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


@dynamic_set_group.command(name=cli_util.override('dynamic_set.update_packages_on_dynamic_set.command_name', 'update-packages'), help=u"""Updates all installed software packages on managed instances in the dynamic set. \n[Command Reference](updatePackagesOnDynamicSet)""")
@cli_util.option('--dynamic-set-id', required=True, help=u"""The [OCID] of the dynamic set. This filter returns resources associated with this dynamic set.""")
@cli_util.option('--update-types', type=custom_types.CliCaseInsensitiveChoice(["SECURITY", "BUGFIX", "ENHANCEMENT", "OTHER", "KSPLICE_KERNEL", "KSPLICE_USERSPACE", "ALL"]), help=u"""The types of updates to be applied.""")
@cli_util.option('--managed-instances', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of managed instance OCIDs to be attached/detached.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--work-request-details', 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(["WAITING", "ACCEPTED", "IN_PROGRESS", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED", "SKIPPED"]), 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 WAITING --wait-for-state SKIPPED 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({'managed-instances': {'module': 'os_management_hub', 'class': 'list[string]'}, 'work-request-details': {'module': 'os_management_hub', 'class': 'WorkRequestDetails'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'managed-instances': {'module': 'os_management_hub', 'class': 'list[string]'}, 'work-request-details': {'module': 'os_management_hub', 'class': 'WorkRequestDetails'}})
@cli_util.wrap_exceptions
def update_packages_on_dynamic_set(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, dynamic_set_id, update_types, managed_instances, work_request_details, if_match):

    if isinstance(dynamic_set_id, six.string_types) and len(dynamic_set_id.strip()) == 0:
        raise click.UsageError('Parameter --dynamic-set-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 update_types is not None:
        _details['updateTypes'] = cli_util.parse_json_parameter("update_types", update_types)

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

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

    client = cli_util.build_client('os_management_hub', 'dynamic_set', ctx)
    result = client.update_packages_on_dynamic_set(
        dynamic_set_id=dynamic_set_id,
        update_packages_on_dynamic_set_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)
