#!/usr/bin/env bash

# This is an unfriendly shell script that generates a file cmd.txt
# with commands to fix #define SIGNATURE_[0-2] lines from <avr/io.h>.
#
# Recognized env:
# MCUS     Set of MCUs.  When not set, then read $builddir/supported-mcus.txt
# CONF     An avrdude.conf or avrdude.conf.in file.  May be invalid
# ATDF     An atdf folder from AtmoChip's atpack.  May be invalid
# srcdir   An AVR-LibC srcdir.  Default is .
# builddir An AVR-LibC builddir.
# CC       Compiler used to preprocess avr/io.h.  Default is avr-gcc.

cmd_file=${1:-cmd.txt}

builddir=${builddir:-../../build/avr-libc}
srcdir=${srcdir:-.}

mcus="${MCUS:-$(cat $builddir/supported-mcus.txt)}"

if [ -z "$mcus" ]; then
    echo "error: no MCUs spefifies"
    echo "$builddir/supported-mcus.txt: not found, set builddir"
    exit 1
fi

CC="${CC:-avr-gcc}"

# As it turns out, AVRDUDE is much more complete w.r.t. signatures
# than AtmoChips' own ATDF files.  Go after avrdude.conf thusly.
conf=${CONF:-$HOME/xgnu/source/avrdude/src/avrdude.conf.in}

echo "mcus=$mcus"

S='[[:space:]]*'

# Preprocess a C file from STDIN with line notes in the outcome.
PreProc ()
{
    $CC -xc - -E -g3 -I$srcdir/include -D__CONFIGURING_AVR_LIBC__ $*
}

echo "# Auto-generated by $0" > ${cmd_file}

for mcu in $mcus; do
    echo ""
    echo "== $mcu"

    # The 1st grep filters for "desc" and "signature" lines.
    # The 2nd grep will yield something like:
    #   desc             = "AT90S2313";
    #   signature        = 0x1e 0x91 0x01;
    grep -e '\(desc\)\|\(signature\)' $conf \
	| grep -i -A1 "desc$S=$S\"$mcu\"" \
	       > sig.txt

    # AVRDUDE is clueless.  Consult ATDF
    if ! grep "signature" sig.txt > /dev/null 2>&1; then
	[ -n "$ATDF" ] || echo '$ATDF is not set'
	[ -d "$ATDF" ] || echo "$ATDF not found"
	atdf=$(find "$ATDF" -iname "$mcu.atdf" | head -1)
	if [ -f "$atdf" ]; then
	    echo ".atdf=$atdf"
	    grep '.*property.*"SIGNATURE[0-2]".*value.*' "$atdf" > sig.txt
	fi
    fi

    cat sig.txt

    # The 1st grep gets line notes and SIGNATURE_[0-2] defs with lines.
    # The 2nd grep keeps the SIGNATURE defs and the preceding line note.
    # Outcome is something like:
    #   1436:# 148 "/home/gnu/source/avr-libc/include/avr/io2313.h"
    #   1664:#define SIGNATURE_0 0x1E
    #   1665:#define SIGNATURE_1 0x91
    #   1666:#define SIGNATURE_2 0x01
    echo '#include <avr/io.h>' | PreProc -mmcu=$mcu \
	| grep -ne '\(^# [0-9]\)\|\(SIGNATURE_[0-2]\)' \
	| grep -B1 SIGNATURE \
	       > loc.txt
    cat loc.txt

    # Proceding with shell is too tedious.  Hand over to Python.
    $(dirname $0)/signats.py sig.txt loc.txt ${cmd_file}
done

echo ""
cat ${cmd_file}
