#!/usr/bin/env bash
# shellcheck disable=SC2162,SC2046,SC2002,SC2034
set -euo pipefail

#
# GovCMS prevent module inclusions in theme dirs.
#
# Inspect the .info.yml files in the repo to determine if there
# are modules preset.
#

GOVCMS_PREVENT_THEME_MODULES=${GOVCMS_PREVENT_THEME_MODULES:-true}
GOVCMS_INFO_FILE_LIST=${GOVCMS_INFO_FILE_LIST:-}
GOVCMS_PREPARE_XML_SCRIPT=${GOVCMS_PREPARE_XML_SCRIPT:-govcms-prepare-xml}
GOVCMS_OUTFILE=${GOVCMS_OUTFILE:-govcms-validate-prevent-theme-modules}
DRUPAL_DIR=${DRUPAL_DIR:-web}

FAILURES=""
function join_char { local IFS="$1" shift; echo "$*"; }

echo "GovCMS Validate :: Scan themes for modules"

# We will need to export this during automated testing.
if [ -z "${GOVCMS_INFO_FILE_LIST}" ]; then
  if [ -d "$DRUPAL_DIR/themes" ]; then
    GOVCMS_INFO_FILE_LIST=$(find "$DRUPAL_DIR/themes" -type f -name "*.info.yml")
  elif [ -d "themes" ]; then
    GOVCMS_INFO_FILE_LIST=$(find themes -type f -name "*.info.yml")
  else
    echo "[info]: No theme folders found."
    exit 0
  fi
fi

if [ "$GOVCMS_PREVENT_THEME_MODULES" = "false" ]; then
  echo "[skip]: Module detection is disabled."
  exit 0;
fi

IFS_BAK="$IFS"
IFS=$'\n'

for file in $GOVCMS_INFO_FILE_LIST; do
  if [[ $(yq r "$file" 'type') == 'module' ]]; then
    echo "[fail]: Module detected with $file"
    FAILURES="$FAILURES,$file"
  fi
  echo "[info]: $file is valid"
done

IFS=$IFS_BAK

if [ -x "${GOVCMS_PREPARE_XML_SCRIPT}" ]; then
  FILE_LFS=$(join_char , "${GOVCMS_INFO_FILE_LIST}")
  ${GOVCMS_PREPARE_XML_SCRIPT} --failures="${FAILURES}" --total="${FILE_LFS}" --name="${GOVCMS_OUTFILE}" --fail-message="GovCMS.QA.FindModule"
fi

if [ -z "${FAILURES}" ]; then
  echo "[success]: No modules detected."
  exit 0
fi

echo "[fail]: Modules detected"
exit 1
