#!/bin/bash
# SPDX-FileCopyrightText: Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.

# skip if doxygen is not installed
if ! [ -x "$(command -v doxygen)" ]; then
  echo -e "warning: Doxygen is not installed"
  exit 0
fi

# Utility to return version as number for comparison
function version { echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }'; }

# Doxygen supported version 1.8.20 to 1.9.1
DOXYGEN_VERSION=$(doxygen --version)
if [ $(version "$DOXYGEN_VERSION") -lt $(version "1.8.20") ] ||  [ $(version $DOXYGEN_VERSION) -gt $(version "1.9.1") ]; then
  echo -e "Warning: Unsupported Doxygen version $DOXYGEN_VERSION"
  echo -e "Expecting Doxygen version from 1.8.20 to 1.9.1"
  exit 0
fi

# Run doxygen, ignore missing tag files error
TAG_ERROR1="error: Tag file '.*.tag' does not exist or is not a file. Skipping it..."
TAG_ERROR2="error: cannot open tag file .*.tag for writing"
DOXYGEN_STDERR=`cd doxygen && { cat Doxyfile ; echo QUIET = YES; echo GENERATE_HTML = NO; }  | doxygen - 2>&1 | sed "/\($TAG_ERROR1\|$TAG_ERROR2\)/d"`
RETVAL=$?

if [ "$RETVAL" != "0" ] || [ ! -z "$DOXYGEN_STDERR" ]; then
  echo -e "\n>>>> FAILED: doxygen check; begin output\n"
  echo -e "$DOXYGEN_STDERR"
  echo -e "\n>>>> FAILED: doxygen check; end output\n"
  RETVAL=1 #because return value is not generated by doxygen 1.8.17
else
  echo -e "\n>>>> PASSED: doxygen check\n"
fi

exit $RETVAL
