#!/bin/bash
# This is a dynamic inventory script for Ansible that pulls host groups from IdM (Identity Management).

# Check if the Kerberos ticket is still valid. If not, shift the arguments (which effectively exits the script).
klist -s || shift $#

# Function to generate and print the inventory list.
list() {
    # Extract the organization domain from the hostname.
    org="$(hostname | sed -E 's|.*\.([^\.]*)\.([^\.]*)$|\1\\.\2|')"

    # Retrieve all host groups from IdM and filter relevant information.
    ipa hostgroup-find --all |
    grep -E 'Host-group:|Member hosts:' |  # Search for lines containing 'Host-group:' or 'Member hosts:'.
    awk 'BEGIN {RS="Host-group: "; FS="\n"}; NR>1 {print $1,$2", "$3}' |  # Process each host group, splitting by lines.
    sed -E 's|(Indirect )?Member hosts:||g; s|([^\.]*)\.[^ ,]*'"$org"'[^ ,]*|\1|g; s|, *$||' |  # Clean up the output.
    awk 'BEGIN {print "{\n    \"_meta\": {\n        \"hostvars\": {}\n    },"} \
        {print "    \""$1"\": {"} \
        {print "        \"hosts\": ["} \
        {for(i=2; i<=NF; ++i) print "            \""$i"\""} \
        {print "        ]\n    },"}' |  # Format the data into a JSON structure expected by Ansible.
    sed 's|,"|",|; ${s|,$|\n}|}'  # Final formatting to correct trailing commas and close JSON object.
}

# Parse the command-line arguments.
case "$1" in
    --list) list ;;  # If the first argument is '--list', call the list function to generate the inventory.
    *) echo '{}' ;;  # If no or invalid argument is given, output an empty JSON object.
esac