#!/usr/bin/env bash

#
# DO NOT EDIT THIS FILE DIRECTLY
#
# It is automatically copied from https://github.com/pion/.goassets repository.
#

set -e

# Disallow usages of functions that cause the program to exit in the library code
SCRIPT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
if [ -f ${SCRIPT_PATH}/.ci.conf ]
then
  . ${SCRIPT_PATH}/.ci.conf
fi

EXCLUDE_DIRECTORIES=${DISALLOWED_FUNCTIONS_EXCLUDED_DIRECTORIES:-"examples"}
DISALLOWED_FUNCTIONS=('os.Exit(' 'panic(' 'Fatal(' 'Fatalf(' 'Fatalln(' 'fmt.Println(' 'fmt.Printf(' 'log.Print(' 'log.Println(' 'log.Printf(')

files=$(
  find "$SCRIPT_PATH/.." -name "*.go" \
    | grep -v -e '^.*_test.go$' \
    | while read file
    do
      excluded=false
      for ex in $EXCLUDE_DIRECTORIES
      do
        if [[ $file == */$ex/* ]]
        then
          excluded=true
          break
        fi
      done
      $excluded || echo "$file"
    done
)

for disallowedFunction in "${DISALLOWED_FUNCTIONS[@]}"
do
	if grep -e "$disallowedFunction" $files | grep -v -e 'nolint'; then
		echo "$disallowedFunction may only be used in example code"
		exit 1
	fi
done
