#!/bin/bash

# Define the directories
directories=("inventory/prod" "inventory/qs" "inventory/lab" "inventory/dev" "inventory/test")

# Function to extract and sort top-level keys from a YAML file using yq
get_top_level_keys() {
    yq eval 'keys | .[]' "$1" | sort
}

# Initialize error code
error_code=0

# Process each file in the base directory and compare its variables across the other directories
find "${directories[0]}" -type f -name '*.yaml' | while read -r base_file; do
    base_relative="${base_file#${directories[0]}}"
    missing_vars=0
    # Extract top-level keys from the base file
    base_keys=$(get_top_level_keys "$base_file")

    for dir in "${directories[@]:1}"; do
        compare_file="$dir$base_relative"
        if [ -f "$compare_file" ]; then
            compare_keys=$(get_top_level_keys "$compare_file")
            diff=$(comm -23 <(echo "$base_keys") <(echo "$compare_keys"))
            if [ ! -z "$diff" ]; then
                echo "Variables  ${compare_file##inventory/} -> ${base_file##inventory/} : $diff"
                ((missing_vars++))
            fi
        else
            echo "File ${base_relative##/group_vars/} missing in $dir"
            ((missing_vars++))
        fi
    done

    if ((missing_vars > error_code)); then
        error_code=$missing_vars
    fi
done

exit $error_code
