#!/usr/bin/env bash

# -------------------------------------------------------------------------------------
#
# Copyright (c) 2022, WSO2 LLC. (https://www.wso2.com). All Rights Reserved.
#
# This software is the property of WSO2 LLC. and its suppliers, if any.
# Dissemination of any information or reproduction of any material contained
# herein in any form is strictly forbidden, unless permitted by WSO2 expressly.
# You may not alter or remove any copyright or other notice from copies of this content.
#
# --------------------------------------------------------------------------------------

# ======================================================================================
# GITHUB CI - Linter Script to analyze the changed files of a PR.
# ======================================================================================

# Inputs
GITHUB_PR_NUMBER=$1

APPS_ROOT_MATCHER="app-extensions"
APPS_ROOT_REPLACER="apps"

# When unsupported file formats are passed in, ESLint throws a warning which conflicts with -max-warnings=0.
# Hence, we need to manually filter out the supported formats.
# Tracker: https://github.com/eslint/eslint/issues/15010
ESLINT_SUPPORTED_EXT=(js jsx ts tsx)

# Check relevant packages are available
command -v pnpm >/dev/null 2>&1 || { echo >&2 "Error: $0 script requires 'pnpm' for buid.  Aborting as not found."; exit 1; }
command -v gh >/dev/null 2>&1 || { echo >&2 "Error: $0 script requires 'gh' to call GitHub APIs.  Aborting as not found."; exit 1; }

raw_changed_files=$(gh pr diff "$GITHUB_PR_NUMBER" --name-only)
changed_files=()
supported_files=()
filer_pattern=""

# Convert the multiline string to a single line.
while read -r file; do
   changed_files+=("$file")
done <<< "$raw_changed_files"

# Filter out the files with the supported extensions.
for file in "${changed_files[@]}"; do
    for ext in "${ESLINT_SUPPORTED_EXT[@]}"; do
        if [[ $file == *$ext ]]; then
            # In the actual target, `app-extensions` is `apps`.
            # With this moderation, app-extensions/console/src/index.ts -> apps/console/src/index.ts
            if [[ $file == $APPS_ROOT_MATCHER* ]]; then
                supported_files+=("${file/$APPS_ROOT_MATCHER/$APPS_ROOT_REPLACER}")
            else
                supported_files+=("$file")
            fi
        fi
    done
done

echo -e "\n============ 💥 Here's what changed in PR#$GITHUB_PR_NUMBER 💥 ============\n"

for file in "${supported_files[@]}"; do
    echo -e "   - $file"
done

echo -e "\n=============================================================\n"

echo -e "🥬 Starting analyzing the changed files with ESLint.."

# Modify the filepattern to avoid eslint pattern mismatch errors.
if [[ ${#supported_files[@]} -gt 1 ]]; then
    filer_pattern="{""$(IFS=","; echo "${supported_files[*]}")""}";
elif [[ ${#supported_files[@]} == 1 ]]; then
    filer_pattern="$(IFS=","; echo "${supported_files[*]}")";
else
    filer_pattern="{}";
fi

pnpm eslint --ext .js,.jsx,.ts,.tsx --no-error-on-unmatched-pattern --max-warnings=0 --resolve-plugins-relative-to . -- "$filer_pattern"
