import click import requests from .cli_main import main, auth_header, base_url from ...schemas import HostgroupParams from ...util.validation import split_and_validate_path @main.group("hostgroup") def hostgroup(): pass @hostgroup.command("list") def hostgroup_list(): click.echo("Listing known hostgroups...") try: response = requests.get(f'{base_url}/hostgroup', headers=auth_header()) response.raise_for_status() click.echo("Hostgroups:") for hg in response.json(): click.echo(f" - {hg}") except requests.exceptions.HTTPError as e: raise click.ClickException(f"Failed to list hostgroups:\n{e}") @hostgroup.command("show") @click.argument("path") def hostgroup_show(path: str): click.echo(f"Showing hostgroup '{path}'...") try: labels = split_and_validate_path(path) name = labels[-1] path = '/'.join(labels[:-1]) if len(labels) > 1 else None data = HostgroupParams( path=path ) response = requests.get(f'{base_url}/hostgroup/{name}', headers=auth_header(), params=data.model_dump()) response.raise_for_status() except requests.exceptions.HTTPError as e: raise click.ClickException(f"Failed to show hostgroup:\n{e}") @hostgroup.command("create") @click.argument("path") def hostgroup_create(path: str): click.echo(f"Creating hostgroup '{path}'...") try: labels = split_and_validate_path(path) path = "/".join(labels[:-1]) if len(labels) > 1 else '' name = labels[-1] data = HostgroupParams( path=path ) response = requests.post(f'{base_url}/hostgroup/{name}', headers=auth_header(), json=data.model_dump()) response.raise_for_status() except requests.exceptions.HTTPError as e: raise click.ClickException(f"Failed to create hostgroup:\n{e}") @hostgroup.command("delete") @click.argument("path") def hostgroup_delete(path: str): click.echo(f"Deleting hostgroup {path}...") try: labels = split_and_validate_path(path) name = labels[-1] prefix = "/".join(labels[:-1]) if len(labels) > 1 else None query_params = f"?path={prefix}" if prefix is not None else '' response = requests.delete(f'{base_url}/hostgroup/{name}{query_params}', headers=auth_header()) response.raise_for_status() except requests.exceptions.HTTPError as e: raise click.ClickException(f"Failed to delete hostgroup:\n{e}")