# Copyright 2021 Google LLC
#
# 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.

set -ex
# Updated files in paths in file_patterns.json will trigger code coverage workflows.
# Updates in a pull request will generate a code coverage report in a PR.
exclude_specs=""
while getopts "p:e:" flag
do
    case "${flag}" in
        p) spec_output_file=${OPTARG};;
        e) exclude_specs=${OPTARG[*]};;
    esac
done

dir=$(pwd)

target_branch_head=$(git rev-parse remotes/origin/${GITHUB_BASE_REF})
echo "The target branch head commit is ${target_branch_head}."
# Set target branch head and this will be used to compare diffs of coverage to the current commit.
echo "::set-output name=target_branch_head::${target_branch_head}"

cd scripts/health_metrics/generate_code_coverage_report

# List changed file from the merged commit. This is generated by comparing the
# merge commit to the head commit from the target branch.
git diff --name-only remotes/origin/${GITHUB_BASE_REF} ${GITHUB_SHA} > updated_files.txt

if [ -z $spec_output_file ] ; then
  swift run UpdatedFilesCollector --changed-file-paths updated_files.txt --code-coverage-file-patterns ../file_patterns.json
else
  swift run UpdatedFilesCollector --changed-file-paths updated_files.txt --code-coverage-file-patterns ../file_patterns.json --output-sdk-file-url "${spec_output_file}" --exclude-podspecs ${exclude_specs}

  mv "${spec_output_file}" "${dir}"
fi
