#!/bin/bash
# shellcheck disable=SC2034,SC2044

# DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
DIR="$(pwd)"

function display_help {
  echo "./$(basename "$0") [ -d | --directory DIRECTORY ] [ -q | --quiet ] [ -h | --help | --vpc-keypair | --lab | --teardown | --redeploy | --clear-logs ] [ OPTIONAL ANSIBLE OPTIONS ]
Script to validate the manifests generated by Kustomize
Where:
  -d  | --directory DIRECTORY  Base directory containing Kustomize overlays
  -e  | --enforce-all-schemas  Enable enforcement of all schemas
  -h  | --help                 Display this help text
  -sl | --schema-location      Location containing schemas"
}

which kustomize && KUSTOMIZE_CMD="kustomize build"

KUSTOMIZE_CMD="${KUSTOMIZE_CMD:-oc kustomize}"
KUSTOMIZE_OPTIONS="--enable-helm"
IGNORE_MISSING_SCHEMAS="--ignore-missing-schemas"
SCHEMA_LOCATION="${DIR}/openshift-json-schema"
KUSTOMIZE_DIRS="${DIR}"
ERROR_COLOR='\033[0;31m'
NO_COLOR='\033[0m'

for i in "$@"
do
  case $i in
    -d=* | --directory=* )
      KUSTOMIZE_DIRS="${i#*=}"
      shift
      ;;
    -e | --enforce-all-schemas )
      shift
      IGNORE_MISSING_SCHEMAS=""
      shift
      ;;
    -sl=* | --schema-location=* )
      SCHEMA_LOCATION="${i#*=}"
      shift
      ;;
    -h | --help )
      display_help
      exit 0
      ;;
  esac
done

errors=0

for i in $(find "${KUSTOMIZE_DIRS}" -name "kustomization.yaml" -exec dirname {} \;)
do
  echo
  echo "Validating $i"
  echo

  if [ -f "$i/.skip_validation" ]; then
    echo "Skipping validation due to .skip_validation marker file"
    continue
  fi

  KUSTOMIZE_BUILD_OUTPUT=$(${KUSTOMIZE_CMD} "$i" $KUSTOMIZE_OPTIONS)

  build_response=$?

  if [ $build_response -ne 0 ]; then
    >&2 echo -e "${ERROR_COLOR}Error building $i${NO_COLOR}"
    errors=$((errors + 1))
  fi

#  echo "$KUSTOMIZE_BUILD_OUTPUT" | kubeval ${IGNORE_MISSING_SCHEMAS} --schema-location="file://${SCHEMA_LOCATION}" --force-color

#  validation_response=$?

#  if [ $validation_response -ne 0 ]; then
#    echo "Error validating $i"
#    exit 1
#  fi
done

echo
if [ $errors -ne 0 ]; then
  echo -e "${ERROR_COLOR}$errors Errors occurred, see logs${NO_COLOR}"
  exit 1
else
  echo "Manifests successfully validated!"
fi
