#!/usr/bin/env bash
set -euo pipefail

#
# GovCMS disallowed permissions check on an active site.
#
# This will get a list of roles from the Drupal database
# to identify if restricted permissions have been given to users.
#

GOVCMS_PREPARE_XML_SCRIPT=${GOVCMS_PREPARE_XML_SCRIPT:-govcms-prepare-xml}
GOVCMS_OUTFILE=${GOVCMS_OUTFILE:-govcms-validate-active-permissions}

FAILURES=""

echo "GovCMS Validate :: Disallowed permissions on active site"

GOVCMS_PERMISSIONS_LIST=$(drush role:list --format=json)
ROLES=$(jq -r '.|[keys[]] | join(",")' <<< "${GOVCMS_PERMISSIONS_LIST}")
RESTRICTED_PERMS_FOUND=$(
  jq -r '[(.|keys[]) as $k
  | if (.[$k].perms |
      index("administer modules") or
      index("administer permissions") or
      index("administer site configuration") or
      index("administer software updates") or
      index("Administer the list of modules that can be managed by others") or
      index("import configuration") or
      index("use PHP for google analytics tracking visibility")
    )
    then {
      role: ($k),
      perms: (.[$k].perms | map(select(. == (
        "administer modules",
        "administer permissions",
        "administer site configuration",
        "administer software updates",
        "Administer the list of modules that can be managed by others",
        "import configuration",
        "use PHP for google analytics tracking visibility"
      ))))
    }
    else empty end]' <<< "${GOVCMS_PERMISSIONS_LIST}")
RESTRICTED_ROLES_FOUND=$(jq -r '.[]|.role' <<< "${RESTRICTED_PERMS_FOUND}")
for role in ${RESTRICTED_ROLES_FOUND}; do
  RESTRICTED_PERMS=$(jq '.[] | select(.role == "'"${role}"'") | .perms | join(",")' <<< "${RESTRICTED_PERMS_FOUND}")
  echo "[fail]: '$role' has restricted permissions: $RESTRICTED_PERMS";
  FAILURES="$FAILURES,$role"
done

if [ -x "${GOVCMS_PREPARE_XML_SCRIPT}" ]; then
  ${GOVCMS_PREPARE_XML_SCRIPT} --failures="${FAILURES}" --total="${ROLES}" --name="${GOVCMS_OUTFILE}" --fail-message="GovCMS.QA.IllegalActivePermissions"
fi

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

echo "[fail]: Elevated permissions detected"
exit 1
