#!/bin/sh
#===----------------------------------------------------------------------===//
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2020 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
#===----------------------------------------------------------------------===//

set -eu

srcroot="$(dirname "$0")"
cd "$srcroot"

gyb="./Utilities/gyb"

# Disable line directives in gyb output. We commit generated sources
# into the package repository, so we do not want absolute file names
# in them.
lineDirective=''

# Uncomment the following line to enable #sourceLocation directives.
# This is useful for local development.
#lineDirective='#sourceLocation(file: "%(file)s", line: %(line)d)'


# Create a temporary directory; remove it on exit.
tmpdir="$(mktemp -d  "${TMPDIR:-/tmp}/$(basename "$0").XXXXXXXX")"
trap "rm -rf \"$tmpdir\"" EXIT

# Run gyb on each gyb file in the source tree and put results in
# subdirectories named 'autogenerated'.
for input in ./Sources/*/*.gyb ./Tests/*/*.gyb; do
    basename="$(basename "$input")"
    targetdir="$(dirname "$input")/autogenerated"
    output="$targetdir/"${basename%.gyb}
    tmpfile="$tmpdir/${basename%.gyb}"

    # Make sure the output directory exists.
    mkdir -p "$targetdir" 

    # Run gyb, making sure to only update files when they change.
    "$gyb" --line-directive "$lineDirective" -o "$tmpfile" "$input"
    if [ -e "$output" ] && cmp -s "$tmpfile" "$output"; then
        : Ignore unchanged file
    else
        echo "Updated $output"
        cp "$tmpfile" "$output"
    fi
    echo "$output" >> "$tmpdir/generated-files.txt"
done

# Warn user if there are any autogenerated files without a corresponding gyb.
find . -path '*/autogenerated/*.swift' >> "$tmpdir/generated-files.txt"
sort "$tmpdir/generated-files.txt" | uniq -u | while read obsolete; do
    echo "Removing $obsolete"
    rm "$obsolete"
done 
