#!/bin/bash
######
# Help
######
show_help()
{
  # Display Help
  echo "Script that calls the endpoint to generate the OpenAPI documentation from core-management and compares the paths against what is already documented."
  echo
  echo "USAGE: checkForUpdatedPaths.sh [-e]"
  echo "-e         Return error code if an error occurs or if new paths are detected or paths are documented that don't exist in the generated OpenAPI documentation."

  exit_with_failure
}

exit_with_failure()
{
  if [ "$ERROR_ON_FAILURE" -eq "1" ]; then
    exit 1
  else
    exit 0
  fi
}

##############
# Main program
##############
ERROR_ON_FAILURE=0

# Parse the arguments
while getopts ":e" o; do
  case "${o}" in
    e) ERROR_ON_FAILURE=1;;
    *) show_help;;
  esac
done
shift $((OPTIND-1))

GENERATED_DOC="target/generated-docs/openapi/openapi.yaml"

if [ ! -f $GENERATED_DOC ]; then
  echo "WARNING: File ${GENERATED_DOC} not found!"
  exit_with_failure
fi

GENERATED_PATHS=$(cat ${GENERATED_DOC})
OPEN_API_BASE_PATH="src/main/resources/static/v2/docs"

PATHS_FROM_ALL_CONTROLLERS=$(grep -E --exclude="*openapi-v3.yaml" --exclude="*openapi-admin-v3.yaml" "^  /" ${OPEN_API_BASE_PATH}/*.yaml | awk -F' ' '{print $2}' | sort)

diffs_detected=0
paths_not_documented=$(comm <(echo "$GENERATED_PATHS" | grep -E "^  /" | grep -Ev "^  /v3" | awk '{print $1}' | sed 's/\/v2//g' | sort) <(echo "$PATHS_FROM_ALL_CONTROLLERS") -2 -3)
if [ -n "$paths_not_documented" ]; then
  diffs_detected=1
  echo "The following paths are not yet documented via OpenAPI:"
  echo "$paths_not_documented"
fi

paths_potentially_removed=$(comm <(echo "$GENERATED_PATHS" | grep -E "^  /" | grep -Ev "^  /v3" | awk '{print $1}' | sed 's/\/v2//g' | sort) <(echo "$PATHS_FROM_ALL_CONTROLLERS") -1 -3)
if [ -n "$paths_potentially_removed" ]; then
  diffs_detected=1
  echo "The following paths are documented via OpenAPI but not detected in the generated OpenAPI spec (possibly removed):"
  echo "$paths_potentially_removed"
fi

PATHS_FROM_INDEX=$(grep -E "^  /" ${OPEN_API_BASE_PATH}/openapi*-v3.yaml | awk -F' ' '{print $2}' | sort)
paths_not_documented_in_index=$(comm <(echo "$PATHS_FROM_INDEX") <(echo "$PATHS_FROM_ALL_CONTROLLERS") -2 -3)
if [ -n "$paths_not_documented_in_index" ]; then
  diffs_detected=1
  echo "The following paths are documented via OpenAPI but are not in openapi-v3.yaml/openapi-admin-v3.yaml:"
  echo "$paths_not_documented_in_index"
fi

paths_in_index_but_not_controllers=$(comm <(echo "$PATHS_FROM_INDEX") <(echo "$PATHS_FROM_ALL_CONTROLLERS") -1 -3)
if [ -n "$paths_in_index_but_not_controllers" ]; then
  diffs_detected=1
  echo "The following paths are documented via OpenAPI but are not in openapi-v3.yaml/openapi-admin-v3.yaml:"
  echo "$paths_in_index_but_not_controllers"
fi

if [ $diffs_detected == 1 ]; then
  exit_with_failure
fi

exit 0
