# generate a file from a source file using a given command.
# a warning not to edit it is automatically added to the created file.
#
# usage: generate <file> <extension> <cmd..>
#
# if an empty extension is provided, the file is modified in-place
# (through a temporary file).
generate() {
    file      >/dev/null 2>&1 || true
    file_tmp  >/dev/null 2>&1 || true
    extension >/dev/null 2>&1 || true

    # get command and target file.
    file="$1"
    extension="$2"
    shift
    shift

    if test -z "$extension"; then
        file_tmp="$file.tmp"
    else
        # we only need this message if we generate a new file.
        printf '%s: generating from "%s" (%s)\n' \
            "$file" "$file$extension" "$1"

        {
            echo '###################################'
            echo '# WARNING! DO NOT EDIT THIS FILE! #'
            echo '###################################'
            echo
            printf '# It was generated from "%s" on %s.\n' \
                "$file$extension" "$(date)"
            echo
        } > "$file"

        file_tmp="$file"
    fi

    # generate $file from $file$extension using the given command.
    "$@" <"$file$extension" >>"$file_tmp"

    if test -z "$extension"; then
        mv "$file_tmp" "$file"
    fi
}


