#!/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}

# Drush 12 support.
DRUSH="${GOVCMS_DRUSH:-none}"
if [ "$DRUSH" == "none" ]; then
  DRUSH=$(which /app/vendor/bin/drush > /dev/null 2>&1 && echo "/app/vendor/bin/drush" || echo "/usr/local/bin/drush")
fi

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 seckit") or
      index("administer site configuration") or
      index("administer software updates") or
      index("import configuration") or
      index("use PHP for google analytics tracking visibility") or
      index("synchronize configuration") or
      index("administer config permissions")
    )
    then {
      role: ($k),
      perms: (.[$k].perms | map(select(. == (
        "administer modules",
        "administer permissions",
        "administer seckit",
        "administer site configuration",
        "administer software updates",
        "import configuration",
        "use PHP for google analytics tracking visibility",
        "synchronize configuration",
        "administer config permissions"
      ))))
    }
    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

# Check the active database for 'is_admin'.
for role in ${ROLES//,/ }; do
  if [[ $("$DRUSH" config:get "user.role.$role" is_admin --format=string) -eq 1 ]]; then
    echo "[FAIL]; '$role' has is_admin";
    FAILURES="$FAILURES,$role"
  fi
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
