#!/bin/sh
# update-from.sh - update a *.FROM provenance-tracking file
# usage: clang --version | ../support/update-from.sh file.FROM
#
# The "versions" part of the file is updated from stdin; the
# "versions-notes" part of the file is updated with a note that it was
# produced with this script; the "persistent-notes" part of the file
# is preserved.
#
# Assumes the existing file is well formed. If it doesn't pass
# check-from.sh, fix it first.

# update this as seems useful
MYVERSION=1

if [ $# != 1 ]; then
    echo "$0: usage: $0 file.FROM" 1>&2
    exit 1
fi

case "$1" in
    *.FROM) FILE="$1";;
    *) echo "$0: file is not named *.FROM" 1>&2; exit 1;;
esac

# Collect stdin and write it to the new file.
(
    echo 'versions'
    sed 's/^/   /'
    echo 'versions-notes'
    echo "   Generated by update-from.sh version $MYVERSION"
) > "$FILE".new

# If the file already exists, propagate any persistent-notes section.
if [ -f "$FILE" ]; then
    awk < "$FILE" >> "$FILE".new '
        BEGIN { see = 0; }
        /^persistent-notes$/ { see = 1; print; next; }
        /^[^ ]/ { see = 0; next; }
        see { print; }
    '
fi

# Move the new file into place.
mv -f "$FILE".new "$FILE"

exit 0
