#!/bin/sh

# Go to git repo root level
cd $(git rev-parse --show-toplevel)

if [[ "$BUILD_DIR" == *"IBDesignables"* ]] || [[ "$BUILD_DIR" == *"Previews"* ]] ; then
    echo "not linting for IBDesignables/SwiftUI Previews builds";
    exit 0
fi

SWIFT_LINT=$(which swiftlint)

if [[ -z $SWIFT_LINT ]] ; then
    echo "warning: SwiftLint not installed, please download it from https://github.com/realm/SwiftLint"
    exit 0
fi
    
if [[ $RUN_CLANG_STATIC_ANALYZER == "YES" ]] ; then
    time $SWIFT_LINT
else
    COUNT=0

    ##### Check for modified git files #####
    FILES=$(git diff --name-only | grep -iv "^carthage" | grep -iv "^pods" | grep -iv "^vendor" | grep -v "R2" | grep ".swift$")
    if [ ! -z "$FILES" ]; then
        while read FILE_PATH; do
            export SCRIPT_INPUT_FILE_$COUNT=$FILE_PATH
            COUNT=$((COUNT + 1))
        done <<< "$FILES"
    fi

    ##### Check for modified files in unstaged/Staged area #####
    FILES=$(git diff --name-only --cached --diff-filter=d | grep -iv "^carthage" | grep -iv "^pods" | grep -iv "^vendor" | grep -v "R2" | grep ".swift$")
    if [ ! -z "$FILES" ]; then
        while read FILE_PATH; do
            export SCRIPT_INPUT_FILE_$COUNT=$FILE_PATH
            COUNT=$((COUNT + 1))
        done <<< "$FILES"
    fi

    ##### Make the count avilable as global variable #####
    export SCRIPT_INPUT_FILE_COUNT=$COUNT
    env | grep SCRIPT_INPUT_FILE_

    if [[ COUNT -ne 0 ]] ; then
        time $SWIFT_LINT --use-script-input-files
    fi
fi
