#!/usr/bin/env 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.
#

# Run Apache RAT on the local repository to check for licenses

set -e

main() {
    local -r source_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    local -r source_top_dir="$(cd "${source_dir}/../../" && pwd)"

    pushd "${source_top_dir}"

    # Generate a temporary archive and validate that, ignores build
    # artifacts (RAT itself doesn't respect .gitignore)
    export ARCHIVE=$(mktemp adbc.ratXXXXXXXX)
    trap 'rm -f "$ARCHIVE"' ERR EXIT INT TERM

    # Need to prefix with directory since check-rat-report.py always removes one layer
    if [[ "$(uname)" = "Darwin" ]]; then
        git ls-files | tar -s '|.*|adbc/~|' --files-from=- --create --gzip --file="${ARCHIVE}"
    else
        git ls-files | tar --transform='s|^|adbc/|' --files-from=- --create --gzip --file="${ARCHIVE}"
    fi

    "${source_top_dir}/dev/release/run-rat.sh" "${ARCHIVE}"

    popd
}

main "$@"
