#!/bin/bash

# NOTE: This is some ugly bash to quickly gather this list, should be made more robust etc.

# Regex to match a GUID string
regexGUID=".*/[0-9A-Za-z]{8}-[0-9A-Za-z]{4}-[0-9A-Za-z]{4}-[0-9A-Za-z]{4}-[0-9A-Za-z]{12}.md$"

# Get path to current folder
folderAll="$( ( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) )"

fileAll="${folderAll}/README.md"

# Write header
{
    printf "%s\n\n" "# All NVRAM Variables"
    printf "%s\n\n" "This is a list of all nvram variables from all files in this repo generated by the script $( basename "$0" )"
    printf "%s\n" "\`\`\`"
} > "${fileAll}"

# Loop through all files in repo whose name matches the 'regexGUID' 
while read file; do
    
    # Loop through all variables in the table 'NVRAM Variables' in the file
    while read variable; do
        
        # If variable is not empty, write it to the file
        if [[ -n ${variable} ]]; then
            printf "%s\n" "$( basename ${file%.*} ):${variable}" >> "${fileAll}"
        fi
    done < <( awk -F\| '/\|:-*\|/ { if (lastline ~ "/\| *Variable   *\|/") {show=1; next}}; {lastline = $0}; /^$/ { show=0 }; show {gsub(/^[ \t]+/,"",$2); print $2}' "${file}" )
done < <( find -E $( dirname "${folderAll}" ) -type f -iregex "${regexGUID}" )

# Write end of variable list
printf "%s\n" "\`\`\`" >> "${fileAll}"

exit 0