#!/usr/bin/env python3

# get_etc_clusters_from_gpli.py
#
# print the list of machines assigned to any GLPI Location in the format
# used by /etc/clusters

import json

import requests

import fuss_glpi


class Client(fuss_glpi.GLPIClient):
    def run(self):
        self.get_token()
        self.discover_computer_search_codes()

        url = f"{self.api_url}/Location"
        r = requests.get(
            url,
            verify=self.ca_cert,
            headers=self.headers,
        )
        locations = json.loads(r.content)
        loc_names = [loc["name"] for loc in locations]

        for name in loc_names:
            url = (
                f"{self.api_url}/search/Computer?"
                "withindexes=true&"
                "criteria[0][field]="
                f"{self.computer_search_fields["location"]}&"
                "criteria[0][searchtype]=contains&"
                f"criteria[0][value]={name}"
            )
            r = requests.get(
                url,
                verify=self.ca_cert,
                headers=self.headers,
            )
            try:
                computers = json.loads(r.content)["data"]
            except KeyError:
                continue

            c_list = [v['1'] for v in computers.values()]

            print(name, " ".join(c_list))


if __name__ == "__main__":
    Client().run()
