#!/bin/sh -
# http://www.berklix.org/~jhs/bin/.sh/make-envs-extract
# Author Julian H. Stacey jhs@berklix 2021-04-24
# This script emits last value of variable names from a cascade of Makefile
# includes. It is called on a single Makefile or include file.
# Sample usage eg:
#	make-envs-extract /etc/make.conf
#	make-envs-extract /etc/src.conf
#	make-envs-extract /usr/src/Makefile

# JJLATER I could add a for loop for multiple filenames,
#	but would I ever need that ?

# JJLATER add a tap & rm before here as 2021-04-25 I saw a monster
# file 693 Meg .make-envs-extract.all.27871.tmp

make -d v $1 2>&1 | grep Global: | sed -e s/Global:// | grep = \
		> $HOME/tmp/.make-envs-extract.$$.all.tmp
	# $HOME/tmp/.make-envs-extract.$$.all.tmp is as yet unsorted,
	# last = assignement is what Makefile will see.
cat $HOME/tmp/.make-envs-extract.$$.all.tmp | awk -F= '{print $1;}' | sort | \
	uniq > $HOME/tmp/.make-envs-extract.$$.names.tmp
cp /dev/null $HOME/tmp/.make-envs-extract.$$.cumulative
for i in `cat $HOME/tmp/.make-envs-extract.$$.names.tmp` ; do
	grep $i $HOME/tmp/.make-envs-extract.$$.all.tmp | tail -1 \
		>> $HOME/tmp/.make-envs-extract.$$.cumulative
	done
rm	$HOME/tmp/.make-envs-extract.$$.all.tmp \
	$HOME/tmp/.make-envs-extract.$$.names.tmp
out=$HOME/tmp/`basename $1`.$$.make-envs-extract
sort $HOME/tmp/.make-envs-extract.$$.cumulative | uniq > $out
rm	$HOME/tmp/.make-envs-extract.$$.cumulative

# echo "Output is not sent to stdout, as with jhs@, this command:"
# echo "	make-envs-extract /etc/make.conf"
# echo "locks the xterm half way through listing binary values in OCR_UMLAUTS"
# OCR_UMLAUTS = | sed -e s/Ö/Oe/g | sed -e s/Ü/ae/g | sed -e s/ß/ss/g | sed -e s/ä/ae/g | sed -e s/é/ae/g | sed -e s/ö/oe/g | sed -e s/ü/ue/g

# echo "Output: $out"
# Removed word Output
echo "$out"
# So I can do eg:
#	cd ~/tmp; \
#	rm -f make.conf.[0-9]*.make-envs-extract \
#	rm -f src.conf.[0-9]*.make-envs-extract \
#	vi \
#	`/home/jhs/bin/.sh/make-envs-extract /etc/make.conf` \
#	`/home/jhs/bin/.sh/make-envs-extract /etc/src.conf`
