#!/usr/bin/env python3

# get_ansible_inventory_from_gpli.py
#
# print an INI format ansible inventory with the machines assigned to
# any GLPI Location and any GLPI Group.

import json

import requests

import fuss_glpi


class Client(fuss_glpi.GLPIClient):
    def search_and_print(self, criterion, names, prefix):
        for name in names:
            print(f"[{prefix}{name}]")
            url = (
                f"{self.api_url}/search/Computer?"
                "withindexes=true&"
                f"criteria[0][field]={self.computer_search_fields[criterion]}&"
                "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

            for i, c in computers.items():
                computer_name = c['1']
                print(f"    {computer_name}")

    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]

        self.search_and_print("location", loc_names, "")

        url = f"{self.api_url}/Group"
        r = requests.get(
            url,
            verify=self.ca_cert,
            headers=self.headers,
        )
        groups = json.loads(r.content)
        group_names = [g["name"] for g in groups]

        self.search_and_print("group", group_names, "group_")


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