#!/bin/bash

################################################################################
##
##  Licensed to the Apache Software Foundation (ASF) under one or more
##  contributor license agreements.  See the NOTICE file distributed with
##  this work for additional information regarding copyright ownership.
##  The ASF licenses this file to You 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.
##
################################################################################

# set the variables
BASE=$(cd "$(dirname "$0")/.." | pwd)
VERSION_RAT="0.14"
RAT_HOME=${BASE}/.rat/apache-rat-${VERSION_RAT}
RAT_JAR=${RAT_HOME}/apache-rat-${VERSION_RAT}.jar
RAT_EXCLUSION=$1

# Validate if the folder is created
if [[ ! -f "${BASE}/.rat" ]]; then
  mkdir -p ${BASE}/.rat
fi

# download the elements required
if [[ ! -f "$RAT_JAR" ]]; then
  cd ${BASE}/.rat
  wget https://dlcdn.apache.org/creadur/apache-rat-${VERSION_RAT}/apache-rat-${VERSION_RAT}-bin.tar.gz
  tar -xvf apache-rat-${VERSION_RAT}-bin.tar.gz
fi

cd ${BASE}
# Set the parameters for rat
rat_opts=("-jar" "${RAT_JAR}" "-d" "${BASE}")

#add the default exclusion for the project
rat_opts+=("-e" "target/*")
rat_opts+=("-e" "^.*.input")
rat_opts+=("-e" "^.*.md")
rat_opts+=("-e" "^.*.iml")
rat_opts+=("-e" "^.*_pb2.py") # code generated by protocol buffer
rat_opts+=("-e" "^.*.properties")
rat_opts+=("-e" "Gemfile.lock")
rat_opts+=("-e" ".gitignore")
rat_opts+=("-e" ".gitmodules")
rat_opts+=("-e" ".rat-excludes")


if [[ ! -z "$RAT_EXCLUSION" ]]; then
   rat_opts+=("-E")
   rat_opts+=($RAT_EXCLUSION)
fi

# execute the validation using rat
java "${rat_opts[@]}"  2>&1 | grep "== File:"