#!/bin/bash
# Copyright 2020 The Tint Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd )"
ROOT_DIR="$( cd "${SCRIPT_DIR}/.." >/dev/null 2>&1 && pwd )"

set -e  # fail on error

if ! command -v clang_format.py &> /dev/null; then
    echo "clang_format.py not found on PATH"
    exit 1
fi

if ! command -v gn &> /dev/null; then
    echo "gn not found on PATH"
    exit 1
fi

CLANG_FORMAT_FILES=""
CLANG_FORMAT_FILES+="`find src -name "*.h"` "
CLANG_FORMAT_FILES+="`find src -name "*.cc"` "
CLANG_FORMAT_FILES+="`find src -name "*.cpp"` "
CLANG_FORMAT_FILES+="`find src -name "*.m"` "
CLANG_FORMAT_FILES+="`find src -name "*.mm"` "
CLANG_FORMAT_FILES+="`find include -name "*.h"` "

GN_FILES="BUILD.gn "
GN_FILES+="`find src -name "*.gn"` "

if command -v go &> /dev/null; then
    # Go is installed. Run in parallel for speed wins
    ${SCRIPT_DIR}/run run-parallel  \
         clang_format.py -i         \
         $ -- $CLANG_FORMAT_FILES

    ${SCRIPT_DIR}/run run-parallel  \
         gn format                  \
         $ -- $GN_FILES
else
    clang_format.py -i $CLANG_FORMAT_FILES
    gn format $GN_FILES
fi