#!/usr/bin/env python3
import argparse
import configparser
import json
import os

from fabric import Connection

script_path = os.path.realpath(__file__)

def parse_ansible_inventory(inventory_file):
    parser = configparser.ConfigParser(allow_no_value=True)
    parser.read(inventory_file)

    inventory_dict = {}

    for section in parser.sections():
        hosts = []
        
        for option in parser.options(section):
            hosts.append(option)

        inventory_dict[section] = hosts

    return inventory_dict

parser = argparse.ArgumentParser(description='Get host system ID')
parser.add_argument('group', type=str, help='Group of hosts to run the command on')
parser.add_argument('host', type=str, help='Host to run the command on', default=None, nargs='?')
args = parser.parse_args()

remote_user = os.environ.get('ANSIBLE_USER', None)
if remote_user is None:
    raise ValueError("ANSIBLE_USER environment variable not set")

inventory_file = f'{os.path.dirname(script_path)}/../inventory/hosts'
inventory_dict = parse_ansible_inventory(inventory_file)

ids = {}
for host in inventory_dict[args.group]:
    if args.host is not None and args.host != host:
        continue
    result = Connection(host, remote_user).run('sudo read_system_id', hide=True)
    ids[host]=(str(result.stdout).strip())
    

print(json.dumps(ids))