# coding: utf-8
# Copyright (c) 2016, 2024, 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('lifecycle_environment.lifecycle_environment_root_group.command_name', 'lifecycle-environment'), cls=CommandGroupWithAlias, help=cli_util.override('lifecycle_environment.lifecycle_environment_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('lifecycle_environment.lifecycle_environment_root_group.short_help', """OS Management Hub API"""))
@cli_util.help_option_group
def lifecycle_environment_root_group():
    pass


@click.command(cli_util.override('lifecycle_environment.lifecycle_stage_group.command_name', 'lifecycle-stage'), cls=CommandGroupWithAlias, help="""Defines the lifecycle stage.""")
@cli_util.help_option_group
def lifecycle_stage_group():
    pass


@click.command(cli_util.override('lifecycle_environment.lifecycle_environment_group.command_name', 'lifecycle-environment'), cls=CommandGroupWithAlias, help="""Defines the lifecycle environment, including the associated versioned software sources, lifecycle stages, and managed instances.""")
@cli_util.help_option_group
def lifecycle_environment_group():
    pass


os_management_hub_service_cli.os_management_hub_service_group.add_command(lifecycle_environment_root_group)
lifecycle_environment_root_group.add_command(lifecycle_stage_group)
lifecycle_environment_root_group.add_command(lifecycle_environment_group)


@lifecycle_stage_group.command(name=cli_util.override('lifecycle_environment.attach_managed_instances_to_lifecycle_stage.command_name', 'attach'), help=u"""Attaches (adds) managed instances to a lifecycle stage. Once added, you can apply operations to all managed instances in the lifecycle stage. \n[Command Reference](attachManagedInstancesToLifecycleStage)""")
@cli_util.option('--lifecycle-stage-id', required=True, help=u"""The [OCID] of the lifecycle stage.""")
@cli_util.option('--managed-instance-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(["ACCEPTED", "IN_PROGRESS", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), 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 SUCCEEDED --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 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-instance-details': {'module': 'os_management_hub', 'class': 'ManagedInstancesDetails'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'managed-instance-details': {'module': 'os_management_hub', 'class': 'ManagedInstancesDetails'}})
@cli_util.wrap_exceptions
def attach_managed_instances_to_lifecycle_stage(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, lifecycle_stage_id, managed_instance_details, if_match):

    if isinstance(lifecycle_stage_id, six.string_types) and len(lifecycle_stage_id.strip()) == 0:
        raise click.UsageError('Parameter --lifecycle-stage-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 managed_instance_details is not None:
        _details['managedInstanceDetails'] = cli_util.parse_json_parameter("managed_instance_details", managed_instance_details)

    client = cli_util.build_client('os_management_hub', 'lifecycle_environment', ctx)
    result = client.attach_managed_instances_to_lifecycle_stage(
        lifecycle_stage_id=lifecycle_stage_id,
        attach_managed_instances_to_lifecycle_stage_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)


@lifecycle_environment_group.command(name=cli_util.override('lifecycle_environment.change_lifecycle_environment_compartment.command_name', 'change-compartment'), help=u"""Moves a lifecycle environment into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment]. \n[Command Reference](changeLifecycleEnvironmentCompartment)""")
@cli_util.option('--lifecycle-environment-id', required=True, help=u"""The [OCID] of the lifecycle environment.""")
@cli_util.option('--compartment-id', help=u"""The [OCID] of the compartment to move the lifecycle environment to.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def change_lifecycle_environment_compartment(ctx, from_json, lifecycle_environment_id, compartment_id, if_match):

    if isinstance(lifecycle_environment_id, six.string_types) and len(lifecycle_environment_id.strip()) == 0:
        raise click.UsageError('Parameter --lifecycle-environment-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 compartment_id is not None:
        _details['compartmentId'] = compartment_id

    client = cli_util.build_client('os_management_hub', 'lifecycle_environment', ctx)
    result = client.change_lifecycle_environment_compartment(
        lifecycle_environment_id=lifecycle_environment_id,
        change_lifecycle_environment_compartment_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@lifecycle_environment_group.command(name=cli_util.override('lifecycle_environment.create_lifecycle_environment.command_name', 'create'), help=u"""Creates a lifecycle environment. A lifecycle environment is a user-defined pipeline to deliver curated, versioned content in a prescribed, methodical manner. \n[Command Reference](createLifecycleEnvironment)""")
@cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment that contains the lifecycle environment.""")
@cli_util.option('--display-name', required=True, help=u"""A user-friendly name for the lifecycle environment. Does not have to be unique and you can change the name later. Avoid entering confidential information.""")
@cli_util.option('--stages', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""User-specified list of ranked lifecycle stages used within the lifecycle environment.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--arch-type', required=True, type=custom_types.CliCaseInsensitiveChoice(["X86_64", "AARCH64", "I686", "NOARCH", "SRC"]), help=u"""The CPU architecture of the managed instances in the lifecycle environment.""")
@cli_util.option('--os-family', required=True, type=custom_types.CliCaseInsensitiveChoice(["ORACLE_LINUX_9", "ORACLE_LINUX_8", "ORACLE_LINUX_7", "ORACLE_LINUX_6", "WINDOWS_SERVER_2016", "WINDOWS_SERVER_2019", "WINDOWS_SERVER_2022", "ALL"]), help=u"""The operating system of the managed instances in the lifecycle environment.""")
@cli_util.option('--vendor-name', required=True, type=custom_types.CliCaseInsensitiveChoice(["ORACLE", "MICROSOFT"]), help=u"""The vendor of the operating system used by the managed instances in the lifecycle environment.""")
@cli_util.option('--description', help=u"""User-specified information about the lifecycle environment. Avoid entering confidential information.""")
@cli_util.option('--location', type=custom_types.CliCaseInsensitiveChoice(["ON_PREMISE", "OCI_COMPUTE", "AZURE", "EC2", "GCP"]), help=u"""The location of managed instances attached to the lifecycle environment. If no location is provided, the default is 'ON_PREMISE.'""")
@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 SUCCEEDED --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({'stages': {'module': 'os_management_hub', 'class': 'list[CreateLifecycleStageDetails]'}, '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={'stages': {'module': 'os_management_hub', 'class': 'list[CreateLifecycleStageDetails]'}, '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': 'LifecycleEnvironment'})
@cli_util.wrap_exceptions
def create_lifecycle_environment(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, display_name, stages, arch_type, os_family, vendor_name, description, location, 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['stages'] = cli_util.parse_json_parameter("stages", stages)
    _details['archType'] = arch_type
    _details['osFamily'] = os_family
    _details['vendorName'] = vendor_name

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

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

    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', 'lifecycle_environment', ctx)
    result = client.create_lifecycle_environment(
        create_lifecycle_environment_details=_details,
        **kwargs
    )
    if wait_for_state:

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


@lifecycle_environment_group.command(name=cli_util.override('lifecycle_environment.delete_lifecycle_environment.command_name', 'delete'), help=u"""Deletes the specified lifecycle environment. \n[Command Reference](deleteLifecycleEnvironment)""")
@cli_util.option('--lifecycle-environment-id', required=True, help=u"""The [OCID] of the lifecycle environment.""")
@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 SUCCEEDED --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_lifecycle_environment(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, lifecycle_environment_id, if_match):

    if isinstance(lifecycle_environment_id, six.string_types) and len(lifecycle_environment_id.strip()) == 0:
        raise click.UsageError('Parameter --lifecycle-environment-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', 'lifecycle_environment', ctx)
    result = client.delete_lifecycle_environment(
        lifecycle_environment_id=lifecycle_environment_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_lifecycle_environment') and callable(getattr(client, 'get_lifecycle_environment')):
            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_lifecycle_environment(lifecycle_environment_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)


@lifecycle_stage_group.command(name=cli_util.override('lifecycle_environment.detach_managed_instances_from_lifecycle_stage.command_name', 'detach'), help=u"""Detaches (removes) a managed instance from a lifecycle stage. \n[Command Reference](detachManagedInstancesFromLifecycleStage)""")
@cli_util.option('--lifecycle-stage-id', required=True, help=u"""The [OCID] of the lifecycle stage.""")
@cli_util.option('--managed-instance-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(["ACCEPTED", "IN_PROGRESS", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), 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 SUCCEEDED --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 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-instance-details': {'module': 'os_management_hub', 'class': 'ManagedInstancesDetails'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'managed-instance-details': {'module': 'os_management_hub', 'class': 'ManagedInstancesDetails'}})
@cli_util.wrap_exceptions
def detach_managed_instances_from_lifecycle_stage(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, lifecycle_stage_id, managed_instance_details, if_match):

    if isinstance(lifecycle_stage_id, six.string_types) and len(lifecycle_stage_id.strip()) == 0:
        raise click.UsageError('Parameter --lifecycle-stage-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 managed_instance_details is not None:
        _details['managedInstanceDetails'] = cli_util.parse_json_parameter("managed_instance_details", managed_instance_details)

    client = cli_util.build_client('os_management_hub', 'lifecycle_environment', ctx)
    result = client.detach_managed_instances_from_lifecycle_stage(
        lifecycle_stage_id=lifecycle_stage_id,
        detach_managed_instances_from_lifecycle_stage_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)


@lifecycle_environment_group.command(name=cli_util.override('lifecycle_environment.get_lifecycle_environment.command_name', 'get'), help=u"""Gets information about the specified lifecycle environment. \n[Command Reference](getLifecycleEnvironment)""")
@cli_util.option('--lifecycle-environment-id', required=True, help=u"""The [OCID] of the lifecycle environment.""")
@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': 'LifecycleEnvironment'})
@cli_util.wrap_exceptions
def get_lifecycle_environment(ctx, from_json, lifecycle_environment_id):

    if isinstance(lifecycle_environment_id, six.string_types) and len(lifecycle_environment_id.strip()) == 0:
        raise click.UsageError('Parameter --lifecycle-environment-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', 'lifecycle_environment', ctx)
    result = client.get_lifecycle_environment(
        lifecycle_environment_id=lifecycle_environment_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@lifecycle_stage_group.command(name=cli_util.override('lifecycle_environment.get_lifecycle_stage.command_name', 'get'), help=u"""Returns information about the specified lifecycle stage. \n[Command Reference](getLifecycleStage)""")
@cli_util.option('--lifecycle-stage-id', required=True, help=u"""The [OCID] of the lifecycle stage.""")
@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': 'LifecycleStage'})
@cli_util.wrap_exceptions
def get_lifecycle_stage(ctx, from_json, lifecycle_stage_id):

    if isinstance(lifecycle_stage_id, six.string_types) and len(lifecycle_stage_id.strip()) == 0:
        raise click.UsageError('Parameter --lifecycle-stage-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', 'lifecycle_environment', ctx)
    result = client.get_lifecycle_stage(
        lifecycle_stage_id=lifecycle_stage_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@lifecycle_environment_group.command(name=cli_util.override('lifecycle_environment.list_lifecycle_environments.command_name', 'list'), help=u"""Lists lifecycle environments that match the specified compartment or lifecycle environment OCID. Filter the list against a variety of criteria including but not limited to its name, status, architecture, and OS family. \n[Command Reference](listLifecycleEnvironments)""")
@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', multiple=True, help=u"""A filter to return resources that match the given display names.""")
@cli_util.option('--display-name-contains', help=u"""A filter to return resources that may partially match the given display name.""")
@cli_util.option('--lifecycle-environment-id', help=u"""The [OCID] of the lifecycle environment.""")
@cli_util.option('--arch-type', type=custom_types.CliCaseInsensitiveChoice(["X86_64", "AARCH64", "I686", "NOARCH", "SRC"]), help=u"""A filter to return only profiles that match the given archType.""")
@cli_util.option('--os-family', type=custom_types.CliCaseInsensitiveChoice(["ORACLE_LINUX_9", "ORACLE_LINUX_8", "ORACLE_LINUX_7", "ORACLE_LINUX_6", "WINDOWS_SERVER_2016", "WINDOWS_SERVER_2019", "WINDOWS_SERVER_2022", "ALL"]), help=u"""A filter to return only resources that match the given operating system family.""")
@cli_util.option('--location', type=custom_types.CliCaseInsensitiveChoice(["ON_PREMISE", "OCI_COMPUTE", "AZURE", "EC2", "GCP"]), multiple=True, help=u"""A filter to return only resources whose location matches the given value.""")
@cli_util.option('--location-not-equal-to', type=custom_types.CliCaseInsensitiveChoice(["ON_PREMISE", "OCI_COMPUTE", "AZURE", "EC2", "GCP"]), multiple=True, help=u"""A filter to return only resources whose location does not match the given 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('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "UPDATING", "ACTIVE", "DELETING", "DELETED", "FAILED"]), help=u"""A filter to return only the lifecycle environments that match the display name given.""")
@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({'display-name': {'module': 'os_management_hub', 'class': 'list[string]'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'display-name': {'module': 'os_management_hub', 'class': 'list[string]'}}, output_type={'module': 'os_management_hub', 'class': 'LifecycleEnvironmentCollection'})
@cli_util.wrap_exceptions
def list_lifecycle_environments(ctx, from_json, all_pages, page_size, compartment_id, display_name, display_name_contains, lifecycle_environment_id, arch_type, os_family, location, location_not_equal_to, limit, page, lifecycle_state, 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 is not None and len(display_name) > 0:
        kwargs['display_name'] = display_name
    if display_name_contains is not None:
        kwargs['display_name_contains'] = display_name_contains
    if lifecycle_environment_id is not None:
        kwargs['lifecycle_environment_id'] = lifecycle_environment_id
    if arch_type is not None:
        kwargs['arch_type'] = arch_type
    if os_family is not None:
        kwargs['os_family'] = os_family
    if location is not None and len(location) > 0:
        kwargs['location'] = location
    if location_not_equal_to is not None and len(location_not_equal_to) > 0:
        kwargs['location_not_equal_to'] = location_not_equal_to
    if limit is not None:
        kwargs['limit'] = limit
    if page is not None:
        kwargs['page'] = page
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    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', 'lifecycle_environment', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@lifecycle_stage_group.command(name=cli_util.override('lifecycle_environment.list_lifecycle_stage_installed_packages.command_name', 'list-lifecycle-stage-installed-packages'), help=u"""Lists installed packages on managed instances in a specified lifecycle stage. Filter the list against a variety of criteria including but not limited to the package name. \n[Command Reference](listLifecycleStageInstalledPackages)""")
@cli_util.option('--lifecycle-stage-id', required=True, help=u"""The [OCID] of the lifecycle stage.""")
@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', multiple=True, help=u"""A filter to return resources that match the given display names.""")
@cli_util.option('--display-name-contains', help=u"""A filter to return resources that may partially match the given display 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('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "UPDATING", "ACTIVE", "DELETING", "DELETED", "FAILED"]), help=u"""A filter to return only lifecycle stages whose lifecycle state matches the given lifecycle state.""")
@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({'display-name': {'module': 'os_management_hub', 'class': 'list[string]'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'display-name': {'module': 'os_management_hub', 'class': 'list[string]'}}, output_type={'module': 'os_management_hub', 'class': 'InstalledPackageCollection'})
@cli_util.wrap_exceptions
def list_lifecycle_stage_installed_packages(ctx, from_json, all_pages, page_size, lifecycle_stage_id, compartment_id, display_name, display_name_contains, limit, page, lifecycle_state, 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(lifecycle_stage_id, six.string_types) and len(lifecycle_stage_id.strip()) == 0:
        raise click.UsageError('Parameter --lifecycle-stage-id cannot be whitespace or empty string')

    kwargs = {}
    if compartment_id is not None:
        kwargs['compartment_id'] = compartment_id
    if display_name is not None and len(display_name) > 0:
        kwargs['display_name'] = display_name
    if display_name_contains is not None:
        kwargs['display_name_contains'] = display_name_contains
    if limit is not None:
        kwargs['limit'] = limit
    if page is not None:
        kwargs['page'] = page
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    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', 'lifecycle_environment', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@lifecycle_stage_group.command(name=cli_util.override('lifecycle_environment.list_lifecycle_stages.command_name', 'list'), help=u"""Lists lifecycle stages that match the specified compartment or lifecycle stage [OCID]. Filter the list against \n[Command Reference](listLifecycleStages)""")
@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', multiple=True, help=u"""A filter to return resources that match the given display names.""")
@cli_util.option('--display-name-contains', help=u"""A filter to return resources that may partially match the given display name.""")
@cli_util.option('--lifecycle-stage-id', help=u"""The [OCID] of the lifecycle stage.""")
@cli_util.option('--software-source-id', help=u"""The [OCID] of the software source. This filter returns resources associated with this software source.""")
@cli_util.option('--arch-type', type=custom_types.CliCaseInsensitiveChoice(["X86_64", "AARCH64", "I686", "NOARCH", "SRC"]), help=u"""A filter to return only profiles that match the given archType.""")
@cli_util.option('--os-family', type=custom_types.CliCaseInsensitiveChoice(["ORACLE_LINUX_9", "ORACLE_LINUX_8", "ORACLE_LINUX_7", "ORACLE_LINUX_6", "WINDOWS_SERVER_2016", "WINDOWS_SERVER_2019", "WINDOWS_SERVER_2022", "ALL"]), help=u"""A filter to return only resources that match the given operating system family.""")
@cli_util.option('--location', type=custom_types.CliCaseInsensitiveChoice(["ON_PREMISE", "OCI_COMPUTE", "AZURE", "EC2", "GCP"]), multiple=True, help=u"""A filter to return only resources whose location matches the given value.""")
@cli_util.option('--location-not-equal-to', type=custom_types.CliCaseInsensitiveChoice(["ON_PREMISE", "OCI_COMPUTE", "AZURE", "EC2", "GCP"]), multiple=True, help=u"""A filter to return only resources whose location does not match the given 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('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "UPDATING", "ACTIVE", "DELETING", "DELETED", "FAILED"]), help=u"""A filter to return only lifecycle stages whose lifecycle state matches the given lifecycle state.""")
@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({'display-name': {'module': 'os_management_hub', 'class': 'list[string]'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'display-name': {'module': 'os_management_hub', 'class': 'list[string]'}}, output_type={'module': 'os_management_hub', 'class': 'LifecycleStageCollection'})
@cli_util.wrap_exceptions
def list_lifecycle_stages(ctx, from_json, all_pages, page_size, compartment_id, display_name, display_name_contains, lifecycle_stage_id, software_source_id, arch_type, os_family, location, location_not_equal_to, limit, page, lifecycle_state, 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 is not None and len(display_name) > 0:
        kwargs['display_name'] = display_name
    if display_name_contains is not None:
        kwargs['display_name_contains'] = display_name_contains
    if lifecycle_stage_id is not None:
        kwargs['lifecycle_stage_id'] = lifecycle_stage_id
    if software_source_id is not None:
        kwargs['software_source_id'] = software_source_id
    if arch_type is not None:
        kwargs['arch_type'] = arch_type
    if os_family is not None:
        kwargs['os_family'] = os_family
    if location is not None and len(location) > 0:
        kwargs['location'] = location
    if location_not_equal_to is not None and len(location_not_equal_to) > 0:
        kwargs['location_not_equal_to'] = location_not_equal_to
    if limit is not None:
        kwargs['limit'] = limit
    if page is not None:
        kwargs['page'] = page
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    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', 'lifecycle_environment', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@lifecycle_stage_group.command(name=cli_util.override('lifecycle_environment.promote_software_source_to_lifecycle_stage.command_name', 'promote-software-source'), help=u"""Updates the versioned custom software source content to the specified lifecycle stage. A versioned custom software source OCID (softwareSourceId) is required when promoting content to the first lifecycle stage. You must promote content to the first stage before promoting to subsequent stages, otherwise the service returns an error. The softwareSourceId is optional when promoting content to the second, third, forth, or fifth stages. If you provide a softwareSourceId, the service validates that it matches the softwareSourceId of the previous stage. If it does not match, the service returns an error. If you don't provide a softwareSourceId, the service promotes the versioned software source from the previous lifecycle stage. If the previous lifecycle stage has no software source, the service returns an error. \n[Command Reference](promoteSoftwareSourceToLifecycleStage)""")
@cli_util.option('--lifecycle-stage-id', required=True, help=u"""The [OCID] of the lifecycle stage.""")
@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('--software-source-id', help=u"""The [OCID] of the software source. This filter returns resources associated with this software source.""")
@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", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), 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 SUCCEEDED --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 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({'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={'work-request-details': {'module': 'os_management_hub', 'class': 'WorkRequestDetails'}})
@cli_util.wrap_exceptions
def promote_software_source_to_lifecycle_stage(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, lifecycle_stage_id, work_request_details, software_source_id, if_match):

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

    kwargs = {}
    if software_source_id is not None:
        kwargs['software_source_id'] = software_source_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'])

    _details = {}

    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', 'lifecycle_environment', ctx)
    result = client.promote_software_source_to_lifecycle_stage(
        lifecycle_stage_id=lifecycle_stage_id,
        promote_software_source_to_lifecycle_stage_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)


@lifecycle_environment_group.command(name=cli_util.override('lifecycle_environment.update_lifecycle_environment.command_name', 'update'), help=u"""Updates the specified lifecycle environment's name, description, stages, or tags. \n[Command Reference](updateLifecycleEnvironment)""")
@cli_util.option('--lifecycle-environment-id', required=True, help=u"""The [OCID] of the lifecycle environment.""")
@cli_util.option('--display-name', help=u"""A user-friendly name for the lifecycle environment. Does not have to be unique. Avoid entering confidential information.""")
@cli_util.option('--description', help=u"""User-specified list of lifecycle stages used within the lifecycle environment. Avoid entering confidential information.""")
@cli_util.option('--stages', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The list of lifecycle stages to be updated.

This option is a JSON list with items of type UpdateLifecycleStageDetails.  For documentation on UpdateLifecycleStageDetails please see our API reference: https://docs.cloud.oracle.com/api/#/en/lifecycleenvironment/20220901/datatypes/UpdateLifecycleStageDetails.""" + 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 SUCCEEDED --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({'stages': {'module': 'os_management_hub', 'class': 'list[UpdateLifecycleStageDetails]'}, '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={'stages': {'module': 'os_management_hub', 'class': 'list[UpdateLifecycleStageDetails]'}, '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': 'LifecycleEnvironment'})
@cli_util.wrap_exceptions
def update_lifecycle_environment(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, lifecycle_environment_id, display_name, description, stages, freeform_tags, defined_tags, if_match):

    if isinstance(lifecycle_environment_id, six.string_types) and len(lifecycle_environment_id.strip()) == 0:
        raise click.UsageError('Parameter --lifecycle-environment-id cannot be whitespace or empty string')
    if not force:
        if stages or freeform_tags or defined_tags:
            if not click.confirm("WARNING: Updates to stages 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 stages is not None:
        _details['stages'] = cli_util.parse_json_parameter("stages", stages)

    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', 'lifecycle_environment', ctx)
    result = client.update_lifecycle_environment(
        lifecycle_environment_id=lifecycle_environment_id,
        update_lifecycle_environment_details=_details,
        **kwargs
    )
    if wait_for_state:

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