#!/usr/bin/env bash
# check-drupal.sh: offline, read-only checker for Drupal core SA-CORE-2026-019 (CVE-2026-136716). Pack 1.0.0 (26 Nov 2026).
# It opens no sockets, writes no files and runs no other program except tr, wc, stat, grep, sed and sort. It reads only the Drupal roots,
# version files and web server config files you name. It never prints the contents of settings.php (no database
# credentials, hash_salt or other secrets). From Drupal.php and composer.lock it reports only the version string.
# Network checks of /core/install.php are not performed; see the README for the manual curl steps Drupal documents.
#
# Usage: check-drupal.sh [--path DIR]... [--version V] [--composer-lock FILE] [--web-user NAME]
#          [--htaccess FILE]... [--apache-conf FILE]... [--nginx-conf FILE]...
#   (-Path, -Version, -ComposerLock, -WebUser, -Htaccess, -ApacheConf and -NginxConf are accepted too)
#
# Exit codes:
#   0 FIXED    every scanned version is a listed fixed release (10.6.23, 11.3.23, 11.4.14 or later on that branch)
#   1          not used (reserved for unexpected runtime errors)
#   2 AFFECTED at least one version is in a supported affected range published by Drupal
#   3 REVIEW   a version could not be classified, sources disagree, or no classifiable version was given
#   4 EOL      no supported affected version, but at least one end-of-life version (Drupal 8, 9, 10.5.x and below,
#              or 11.2.x and below)
#   5 USAGE OR READ ERROR
set -u
export LC_ALL=C

VERSION_TAG="check-drupal-sa-core-2026-019 1.0.0"
MAX_SMALL=1048576
MAX_CONF=8388608
MAX_LINE=8192

usage() {
  echo 'Usage: check-drupal.sh [--path DIR]... [--version V] [--composer-lock FILE] [--web-user NAME] [--htaccess FILE]... [--apache-conf FILE]... [--nginx-conf FILE]...'
  echo 'Offline and read-only. Exit codes: 0 FIXED, 2 AFFECTED, 3 REVIEW, 4 EOL, 5 USAGE OR READ ERROR (1 is not used).'
}
die() { echo "ERROR: $*"; exit 5; }
clean_path() { printf '%s' "$1" | LC_ALL=C tr -c '\40-\176' '?'; }
need() { [ "$1" -ge 2 ] || die "$2 option needs a value"; }

# read_lines FILE MAX: fills LINES (NUL becomes space, trailing CR dropped). Long lines are kept but parsers ignore them.
# check_file FILE MAX: the same checks as read_lines, run in the main shell so an error stops the whole run.
check_file() {
  local f=$1 max=$2 sz
  { [ -f "$f" ] && [ -r "$f" ]; } || die "file not found or unreadable: $(clean_path "$f")"
  [ ! -L "$f" ] || die "file is a symlink (not followed): $(clean_path "$f")"
  sz=$(wc -c < "$f" 2>/dev/null) || die "file unreadable: $(clean_path "$f")"
  [ "$sz" -le "$max" ] || die "file too large: $(clean_path "$f")"
}
read_lines() {
  local f=$1 max=$2 l
  check_file "$f" "$max"
  LINES=()
  while IFS= read -r l || [ -n "$l" ]; do LINES+=("${l%$'\r'}"); done < <(tr '\000' ' ' < "$f")
}

posix_meta() {
  # sets MODE OWNER GROUP from a file or directory; does not read file content.
  local f=$1
  MODE=""; OWNER=""; GROUP=""
  { [ -e "$f" ] && [ ! -L "$f" ]; } || return 1
  MODE=$(stat -c '%a' "$f" 2>/dev/null) || return 1
  OWNER=$(stat -c '%U' "$f" 2>/dev/null) || return 1
  GROUP=$(stat -c '%G' "$f" 2>/dev/null) || return 1
  return 0
}

# writable_msg MODE OWNER GROUP: uses WEB_USER
writable_msg() {
  local mode=$1 owner=$2 group=$3 ow gw ww
  # last three octal digits (ignore setuid bits for the write checks of the low bits)
  local last
  last=${mode: -3}
  [ ${#last} -eq 3 ] || last=$(printf '%03d' "$mode" 2>/dev/null || echo "$mode")
  ow=0; gw=0; ww=0
  case ${last:0:1} in 2|3|6|7) ow=1;; esac
  case ${last:1:1} in 2|3|6|7) gw=1;; esac
  case ${last:2:1} in 2|3|6|7) ww=1;; esac
  if [ -z "$WEB_USER" ]; then
    if [ "$ww" = 1 ]; then echo "UNKNOWN (pass --web-user to assess); OTHER_WRITABLE YES"
    else echo "UNKNOWN (pass --web-user to assess); OTHER_WRITABLE NO"; fi
    return
  fi
  if [ "$ww" = 1 ]; then echo "YES (world-write)"; return; fi
  if [ "$ow" = 1 ] && [ "$owner" = "$WEB_USER" ]; then echo "YES (owner-write, owner matches --web-user $WEB_USER)"; return; fi
  if [ "$gw" = 1 ] && [ "$group" = "$WEB_USER" ]; then echo "YES (group-write, group matches --web-user $WEB_USER)"; return; fi
  echo "NO"
}

# show_ver VERSION: prints the version only if it looks like a release number, so other input is never echoed.
VER_RX='^[0-9]+\.[0-9]+(\.[0-9]+)?([.-][A-Za-z0-9._-]+)?$'
show_ver() { if [[ $1 =~ $VER_RX ]]; then printf '%s' "$1"; else printf '%s' '(not shown: not a version string)'; fi; }

# classify VERSION: prints "STATUS|reason"

classify() {
  local raw=$1 major minor patch rest suffix
  if ! [[ $raw =~ $VER_RX ]]; then
    echo "REVIEW|the version string is not a plain Drupal core release number (unparseable, not shown)"
    return
  fi
  IFS=. read -r major minor rest <<<"$raw"
  patch=0; suffix=""
  if [ -n "${rest:-}" ]; then
    if printf '%s' "$rest" | grep -qE '^[0-9]+'; then
      patch=${rest%%[.-]*}
      suffix=${rest#"$patch"}
    else
      suffix=".$rest"
    fi
  fi
  # suffix may also be attached to minor when no patch: 11.4-dev is unusual; treat via rest.
  if printf '%s' "$minor" | grep -qE '[^0-9]'; then
    echo "REVIEW|the version string is not a plain Drupal core release number (unparseable, not shown)"
    return
  fi
  if ! printf '%s' "$major$minor$patch" | grep -qE '^[0-9]+$'; then
    echo "REVIEW|the version string is not a plain Drupal core release number (unparseable, not shown)"
    return
  fi
  major=$((10#$major)); minor=$((10#$minor)); patch=$((10#$patch))
  if [ "$major" -le 7 ]; then
    echo "EOL|$raw is end-of-life (Drupal $major has no security coverage); the CVE record's affected range starts at 0.0.0 and no fix is published for it"
    return
  fi
  if [ "$major" -eq 8 ] || [ "$major" -eq 9 ]; then
    echo "EOL|$raw: Drupal 8 and Drupal 9 have reached end-of-life; the advisory's affected range includes versions below 10.6.23"
    return
  fi
  if [ "$major" -eq 10 ]; then
    if [ "$minor" -le 5 ]; then
      echo "EOL|$raw is on an end-of-life branch (Drupal 10.5.x and below have no security coverage); the advisory's affected range includes versions below 10.6.23. Migrate to 10.6.23 or a supported Drupal 11 release"
      return
    fi
    if [ "$minor" -eq 6 ]; then
      if [ -n "$suffix" ] && [ "$patch" -ge 23 ]; then
        echo "REVIEW|$raw has a pre-release or extra suffix; the advisory lists released version 10.6.23"
        return
      fi
      if [ "$patch" -lt 23 ]; then
        echo "AFFECTED|$raw is below 10.6.23; upgrade to 10.6.23, then run update.php"
        return
      fi
      echo "FIXED|$raw is at or above 10.6.23, the fixed release for Drupal 10.6.x; run update.php"
      return
    fi
    echo "REVIEW|$raw is a 10.x branch not listed in the 25 Nov 2026 advisory"
    return
  fi
  if [ "$major" -eq 11 ]; then
    if [ "$minor" -le 2 ]; then
      echo "EOL|$raw is on an end-of-life branch (Drupal 11.2.x and below have no security coverage); the advisory's affected range includes 11.0.0 to below 11.3.23. Migrate to 11.3.23 or 11.4.14"
      return
    fi
    if [ "$minor" -eq 3 ]; then
      if [ -n "$suffix" ] && [ "$patch" -ge 23 ]; then
        echo "REVIEW|$raw has a pre-release or extra suffix; the advisory lists released version 11.3.23"
        return
      fi
      if [ "$patch" -lt 23 ]; then
        echo "AFFECTED|$raw is below 11.3.23; upgrade to 11.3.23, then run update.php"
        return
      fi
      echo "FIXED|$raw is at or above 11.3.23, the fixed release for Drupal 11.3.x; run update.php"
      return
    fi
    if [ "$minor" -eq 4 ]; then
      if [ -n "$suffix" ] && [ "$patch" -ge 14 ]; then
        echo "REVIEW|$raw has a pre-release or extra suffix; the advisory lists released version 11.4.14"
        return
      fi
      if [ "$patch" -lt 14 ]; then
        echo "AFFECTED|$raw is below 11.4.14; upgrade to 11.4.14, then run update.php"
        return
      fi
      echo "FIXED|$raw is at or above 11.4.14, the fixed release for Drupal 11.4.x; run update.php"
      return
    fi
    echo "REVIEW|$raw is an 11.x branch not listed in the 25 Nov 2026 advisory"
    return
  fi
  echo "REVIEW|$raw is a major branch not listed in the 25 Nov 2026 advisory"
}

extract_drupal_php_version() {
  # uses LINES; prints version or empty
  local l v
  for l in "${LINES[@]}"; do
    [ ${#l} -le "$MAX_LINE" ] || continue
    v=$(printf '%s' "$l" | sed -nE "s/^[[:space:]]*const[[:space:]]+VERSION[[:space:]]*=[[:space:]]*['\"]([^'\"]+)['\"].*/\1/p")
    if [ -n "$v" ]; then printf '%s' "$v"; return; fi
  done
}

extract_bootstrap_version() {
  local l v
  for l in "${LINES[@]}"; do
    [ ${#l} -le "$MAX_LINE" ] || continue
    v=$(printf '%s' "$l" | sed -nE "s/^[[:space:]]*define\([[:space:]]*['\"]VERSION['\"][[:space:]]*,[[:space:]]*['\"]([^'\"]+)['\"].*/\1/p")
    if [ -n "$v" ]; then printf '%s' "$v"; return; fi
  done
}

extract_lock_version() {
  local l name=0 t
  for l in "${LINES[@]}"; do
    [ ${#l} -le "$MAX_LINE" ] || continue
    t=$(printf '%s' "$l" | sed -nE 's/^[[:space:]]*"name"[[:space:]]*:[[:space:]]*"([^"]+)"[[:space:]]*,?[[:space:]]*$/\1/p')
    if [ -n "$t" ]; then
      if [ "$t" = "drupal/core" ]; then name=1
      else name=0; fi
      continue
    fi
    t=$(printf '%s' "$l" | sed -nE 's/^[[:space:]]*"version"[[:space:]]*:[[:space:]]*"([^"]+)"[[:space:]]*,?[[:space:]]*$/\1/p')
    if [ -n "$t" ] && [ "$name" = 1 ]; then printf '%s' "$t"; return; fi
  done
}

# strip_hash_comment: remove unquoted # comments (best effort)
strip_comment() {
  printf '%s' "$1" | sed -E 's/[[:space:]]#.*$//; s/^#.*$//'
}

scan_apache() {
  # uses LINES; prints verdict word and detail
  local l s inside=0 blocked=0 partial=0 other=0
  for l in "${LINES[@]}"; do
    [ ${#l} -le "$MAX_LINE" ] || continue
    s=$(strip_comment "$l")
    s=${s#"${s%%[![:space:]]*}"}; s=${s%"${s##*[![:space:]]}"}
    [ -n "$s" ] || continue
    if printf '%s' "$s" | grep -qiE '^<Location[[:space:]]+["'\''/][^"'\'']*install\.php'; then inside=1; continue; fi
    if printf '%s' "$s" | grep -qiE '^<Files[[:space:]]+["'\'']?install\.php["'\'']?'; then inside=1; continue; fi
    if printf '%s' "$s" | grep -qiE '^</(Location|Files)>'; then inside=0; continue; fi
    if [ "$inside" = 1 ]; then
      if printf '%s' "$s" | grep -qiE '^Require[[:space:]]+all[[:space:]]+denied'; then blocked=1
      elif printf '%s' "$s" | grep -qiE '^Require[[:space:]]+ip\b'; then partial=1
      elif printf '%s' "$s" | grep -qiE '^Require[[:space:]]'; then other=1
      fi
    fi
  done
  if [ "$blocked" = 1 ]; then echo "BLOCKED|documented Require all denied for install.php"
  elif [ "$partial" = 1 ]; then echo "PARTIAL|Require ip allowlist for install.php (not a full block)"
  elif [ "$other" = 1 ]; then echo "RULE_PRESENT|an install.php Require rule is present but it is not Require all denied"
  else echo "NO_RULE|no documented install.php Location or Files block"; fi
}

scan_nginx() {
  local l s inside=0 style="" blocked=0 incomplete=0 other=0
  for l in "${LINES[@]}"; do
    [ ${#l} -le "$MAX_LINE" ] || continue
    s=$(strip_comment "$l")
    s=${s#"${s%%[![:space:]]*}"}; s=${s%"${s##*[![:space:]]}"}
    [ -n "$s" ] || continue
    if printf '%s' "$s" | grep -qE '^location[[:space:]]+'; then
      inside=0; style=""
      if printf '%s' "$s" | grep -qE '^location[[:space:]]+\^~[[:space:]]+[^;]*install\.php'; then inside=1; style=prefix
      elif printf '%s' "$s" | grep -qE '^location[[:space:]]+=[[:space:]]+[^;]*install\.php'; then inside=1; style=exact
      elif printf '%s' "$s" | grep -qE '^location[[:space:]]+.*install\.php'; then inside=1; style=other
      fi
      if [ "$inside" = 1 ] && printf '%s' "$s" | grep -q '}'; then
        if printf '%s' "$s" | grep -qE 'return[[:space:]]+40[34]'; then
          if [ "$style" = prefix ]; then blocked=1
          elif [ "$style" = exact ]; then incomplete=1
          else other=1; fi
        elif [ "$style" = exact ]; then incomplete=1
        else other=1; fi
        inside=0
      fi
      continue
    fi
    if [ "$inside" = 1 ]; then
      if printf '%s' "$s" | grep -qE '^return[[:space:]]+40[34]'; then
        if [ "$style" = prefix ]; then blocked=1
        elif [ "$style" = exact ]; then incomplete=1
        else other=1; fi
      elif printf '%s' "$s" | grep -qE '^(deny[[:space:]]+all|return[[:space:]])'; then
        other=1
      fi
      if printf '%s' "$s" | grep -q '}'; then inside=0; fi
    fi
  done
  if [ "$blocked" = 1 ]; then echo "BLOCKED|documented location ^~ .../core/install.php with return 403 or 404"
  elif [ "$incomplete" = 1 ]; then echo "INCOMPLETE|location = .../core/install.php (Drupal says an exact match may not block /core/install.php/foo)"
  elif [ "$other" = 1 ]; then echo "RULE_PRESENT|an install.php location is present but it is not the documented ^~ plus return 404 rule"
  else echo "NO_RULE|no documented install.php location"; fi
}

PATHS=(); OPT_VERS=(); LOCKS=(); WEB_USER=""; HTACCESS=(); APACHE=(); NGINX=()
while [ $# -gt 0 ]; do
  case $1 in
    --path|-Path) need $# path; [ -n "$2" ] || die "path option needs a value"; PATHS+=("$2"); shift 2;;
    --version|-Version) need $# version; [ -n "$2" ] || die "version option needs a value"; OPT_VERS+=("$2"); shift 2;;
    --composer-lock|-ComposerLock) need $# composer-lock; [ -n "$2" ] || die "composer-lock option needs a value"; LOCKS+=("$2"); shift 2;;
    --web-user|-WebUser) need $# web-user; [ -n "$2" ] || die "web-user option needs a value"; WEB_USER=$2; shift 2;;
    --htaccess|-Htaccess) need $# htaccess; [ -n "$2" ] || die "htaccess option needs a value"; HTACCESS+=("$2"); shift 2;;
    --apache-conf|-ApacheConf) need $# apache-conf; [ -n "$2" ] || die "apache-conf option needs a value"; APACHE+=("$2"); shift 2;;
    --nginx-conf|-NginxConf) need $# nginx-conf; [ -n "$2" ] || die "nginx-conf option needs a value"; NGINX+=("$2"); shift 2;;
    -h|--help|-Help) usage; exit 5;;
    *) die "unknown option: $(clean_path "$1")";;
  esac
done
if [ ${#PATHS[@]} -eq 0 ] && [ ${#OPT_VERS[@]} -eq 0 ] && [ ${#LOCKS[@]} -eq 0 ]; then usage; exit 5; fi

echo "CHECKER: $VERSION_TAG"
echo "CVE: CVE-2026-136716 (SA-CORE-2026-019, a follow-on to SA-CORE-2026-017)"
echo "SCORE: Drupal rates it Highly critical (21/25 on Drupal's risk scale: AC:Basic/A:None/CI:All/II:All/E:Exploit/TD:Uncommon). No CVSS score is published: the CVE.org record has no metrics and NVD shows Received with no metrics, checked 07:40 GMT on 26 Nov 2026."
echo "KEV: not listed in CISA KEV as of the 25 Nov 2026 catalogue (dateReleased 25 Nov 2026, 19:48 GMT), checked 07:40 GMT on 26 Nov 2026. SA-CORE-2026-017 (CVE-2026-132165) is listed, added 24 Nov 2026 with due date 27 Nov 2026. KEV due dates apply to US federal agencies only (BOD 26-04). Patch now regardless."
echo 'EXPLOITATION: Drupal says "This is being exploited in the wild." Sites that left the installer remotely accessible after SA-CORE-2026-017 may already be compromised.'

ANY_AFF=0; ANY_EOL=0; ANY_REV=0; ANY_FIX=0
record() {
  case $1 in
    AFFECTED) ANY_AFF=1;;
    EOL) ANY_EOL=1;;
    REVIEW) ANY_REV=1;;
    FIXED) ANY_FIX=1;;
  esac
}

resolve_root() {
  # sets ROOT from $1
  local p=$1
  [ -d "$p" ] || die "path not found or not a directory: $(clean_path "$p")"
  [ ! -L "$p" ] || die "path is a symlink (not followed): $(clean_path "$p")"
  if [ -f "$p/core/lib/Drupal.php" ] && [ ! -L "$p/core/lib/Drupal.php" ]; then ROOT=$p; return; fi
  if [ -f "$p/web/core/lib/Drupal.php" ] && [ ! -L "$p/web/core/lib/Drupal.php" ]; then ROOT=$p/web; return; fi
  if [ -f "$p/docroot/core/lib/Drupal.php" ] && [ ! -L "$p/docroot/core/lib/Drupal.php" ]; then ROOT=$p/docroot; return; fi
  if [ -f "$p/includes/bootstrap.inc" ] && [ ! -L "$p/includes/bootstrap.inc" ]; then ROOT=$p; return; fi
  if [ -f "$p/composer.lock" ] && [ ! -L "$p/composer.lock" ]; then ROOT=$p; return; fi
  die "does not look like a Drupal root or Composer project (no core/lib/Drupal.php, includes/bootstrap.inc or composer.lock): $(clean_path "$p")"
}

emit_status() {
  local r=$1
  record "${r%%|*}"
  echo "STATUS: ${r%%|*} (${r#*|})"
}

scan_conf_file() {
  local kind=$1 f=$2 res
  read_lines "$f" "$MAX_CONF"
  if [ "$kind" = nginx ]; then res=$(scan_nginx)
  else res=$(scan_apache); fi
  echo "$res"
}

# supplied extra configs (printed once after sites, also used per site for auto htaccess)
print_supplied_confs() {
  local f res
  for f in "${HTACCESS[@]+"${HTACCESS[@]}"}"; do
    check_file "$f" "$MAX_CONF"; res=$(scan_conf_file apache "$f")
    echo "HTACCESS: ${res%%|*} (${res#*|}, in $(clean_path "$f"))"
  done
  for f in "${APACHE[@]+"${APACHE[@]}"}"; do
    check_file "$f" "$MAX_CONF"; res=$(scan_conf_file apache "$f")
    echo "APACHE: ${res%%|*} (${res#*|}, in $(clean_path "$f"))"
  done
  for f in "${NGINX[@]+"${NGINX[@]}"}"; do
    check_file "$f" "$MAX_CONF"; res=$(scan_conf_file nginx "$f")
    echo "NGINX: ${res%%|*} (${res#*|}, in $(clean_path "$f"))"
  done
}

for v in "${OPT_VERS[@]+"${OPT_VERS[@]}"}"; do
  echo "SITE: (version only)"
  echo "VERSION: $(show_ver "$v") (from --version)"
  emit_status "$(classify "$v")"
done

for lf in "${LOCKS[@]+"${LOCKS[@]}"}"; do
  read_lines "$lf" "$MAX_CONF"
  lv=$(extract_lock_version)
  echo "SITE: (composer.lock only)"
  if [ -z "$lv" ]; then
    echo "LOCK_VERSION: (none) (no drupal/core version in $(clean_path "$lf"))"
    emit_status "REVIEW|composer.lock did not contain a drupal/core version"
  else
    echo "LOCK_VERSION: $(show_ver "$lv") (from $(clean_path "$lf"))"
    emit_status "$(classify "$lv")"
  fi
done

for p in "${PATHS[@]+"${PATHS[@]}"}"; do
  resolve_root "$p"
  echo "SITE: $(clean_path "$p")"
  echo "ROOT: $(clean_path "$ROOT")"
  php_ver=""; php_src=""; lock_ver=""; lock_src=""
  if [ -f "$ROOT/core/lib/Drupal.php" ]; then
    [ -L "$ROOT/core/lib/Drupal.php" ] && die "file is a symlink (not followed): $(clean_path "$ROOT/core/lib/Drupal.php")"
    read_lines "$ROOT/core/lib/Drupal.php" "$MAX_SMALL"
    php_ver=$(extract_drupal_php_version)
    php_src="core/lib/Drupal.php"
  elif [ -f "$ROOT/includes/bootstrap.inc" ]; then
    [ -L "$ROOT/includes/bootstrap.inc" ] && die "file is a symlink (not followed): $(clean_path "$ROOT/includes/bootstrap.inc")"
    read_lines "$ROOT/includes/bootstrap.inc" "$MAX_SMALL"
    php_ver=$(extract_bootstrap_version)
    php_src="includes/bootstrap.inc"
  fi
  # composer.lock at the given path, the root, or the parent of a web/docroot
  for cand in "$p/composer.lock" "$ROOT/composer.lock" "$ROOT/../composer.lock"; do
    if [ -f "$cand" ] && [ ! -L "$cand" ]; then
      read_lines "$cand" "$MAX_CONF"
      lock_ver=$(extract_lock_version)
      if [ -n "$lock_ver" ]; then lock_src=$(clean_path "$cand"); break; fi
    fi
  done
  if [ -n "$php_ver" ]; then echo "VERSION: $(show_ver "$php_ver") (from $php_src)"; fi
  if [ -n "$lock_ver" ]; then echo "LOCK_VERSION: $(show_ver "$lock_ver") (from $lock_src)"; fi
  if [ -z "$php_ver" ] && [ -z "$lock_ver" ]; then
    emit_status "REVIEW|no core version found in Drupal.php, bootstrap.inc or composer.lock"
  elif [ -n "$php_ver" ] && [ -n "$lock_ver" ] && [ "$php_ver" != "$lock_ver" ]; then
    echo "STATUS: REVIEW (Drupal.php has $(show_ver "$php_ver") but composer.lock has $(show_ver "$lock_ver"))"
    record REVIEW
  elif [ -n "$php_ver" ]; then
    emit_status "$(classify "$php_ver")"
  else
    emit_status "$(classify "$lock_ver")"
  fi

  if [ -e "$ROOT/core/install.php" ]; then
    if [ -L "$ROOT/core/install.php" ]; then echo "INSTALL_PHP: SYMLINK (core/install.php; not followed)"
    elif [ -f "$ROOT/core/install.php" ]; then echo "INSTALL_PHP: PRESENT (core/install.php; Drupal recommends blocking it at the web server and removing it)"
    else echo "INSTALL_PHP: PRESENT (core/install.php exists, not a regular file)"; fi
  else
    echo "INSTALL_PHP: ABSENT (core/install.php not found)"
  fi
  if [ -L "$ROOT/install.php" ]; then echo "INSTALL_PHP_ROOT: SYMLINK (install.php in the Drupal root; not followed)"
  elif [ -f "$ROOT/install.php" ]; then echo "INSTALL_PHP_ROOT: PRESENT (install.php in the Drupal root)"
  elif [ -e "$ROOT/install.php" ]; then echo "INSTALL_PHP_ROOT: PRESENT (install.php in the Drupal root, not a regular file)"
  fi

  sd="$ROOT/sites/default"
  if [ -d "$sd" ] && [ ! -L "$sd" ]; then
    if posix_meta "$sd"; then
      echo "SITES_DEFAULT: mode $MODE owner $OWNER:$GROUP"
      echo "WRITABLE_SITES_DEFAULT: $(writable_msg "$MODE" "$OWNER" "$GROUP")"
    else
      echo "SITES_DEFAULT: PRESENT (mode unknown)"
      echo "WRITABLE_SITES_DEFAULT: UNKNOWN (POSIX mode not available)"
      record REVIEW
    fi
  elif [ -L "$sd" ]; then
    echo "SITES_DEFAULT: SYMLINK (not followed)"
  else
    echo "SITES_DEFAULT: ABSENT"
  fi

  # settings.php under sites/<site>/ only (one level); do not follow symlinks; never read content
  shopt -s nullglob
  sets=("$ROOT"/sites/*/settings.php)
  shopt -u nullglob
  if [ ${#sets[@]} -eq 0 ]; then
    echo "SETTINGS: ABSENT"
  else
    # sort for stable output
    mapfile -t sets_sorted < <(printf '%s\n' "${sets[@]}" | LC_ALL=C sort)
    for sf in "${sets_sorted[@]}"; do
      rel=${sf#"$ROOT/"}
      if [ -L "$sf" ]; then
        echo "SETTINGS: SYMLINK $(clean_path "$rel") (not followed, content not read)"
        continue
      fi
      if [ ! -f "$sf" ]; then
        echo "SETTINGS: PRESENT $(clean_path "$rel") (not a regular file, content not read)"
        continue
      fi
      if posix_meta "$sf"; then
        echo "SETTINGS: PRESENT $(clean_path "$rel") mode $MODE owner $OWNER:$GROUP (content not read)"
        echo "WRITABLE_SETTINGS: $(clean_path "$rel"): $(writable_msg "$MODE" "$OWNER" "$GROUP")"
      else
        echo "SETTINGS: PRESENT $(clean_path "$rel") (mode unknown, content not read)"
        echo "WRITABLE_SETTINGS: $(clean_path "$rel"): UNKNOWN (POSIX mode not available)"
        record REVIEW
      fi
    done
  fi

  auto_ht=$ROOT/.htaccess
  if [ -f "$auto_ht" ] && [ ! -L "$auto_ht" ]; then
    check_file "$auto_ht" "$MAX_CONF"; res=$(scan_conf_file apache "$auto_ht")
    echo "HTACCESS: ${res%%|*} (${res#*|}, in $(clean_path "$auto_ht"))"
  elif [ -L "$auto_ht" ]; then
    echo "HTACCESS: SYMLINK (not followed)"
  else
    echo "HTACCESS: ABSENT (no .htaccess in the Drupal root)"
  fi
done

# Supplied confs are reported once (they apply to the estate, not only one root)
if [ ${#PATHS[@]} -gt 0 ] || [ ${#HTACCESS[@]} -gt 0 ] || [ ${#APACHE[@]} -gt 0 ] || [ ${#NGINX[@]} -gt 0 ]; then
  print_supplied_confs
fi

echo "NOTE: this checker does not probe install.php over the network. Use the manual curl steps in the README."
echo "NOTE: Drupal says an update hook must run (update.php) to fix existing production sites in this state. A fixed code version does not show that update.php has run or that user 1 is unchanged; audit user 1 (email and password) and the access logs."

if [ "$ANY_AFF" = 1 ]; then overall=AFFECTED; rc=2
elif [ "$ANY_EOL" = 1 ]; then overall=EOL; rc=4
elif [ "$ANY_REV" = 1 ]; then overall=REVIEW; rc=3
elif [ "$ANY_FIX" = 1 ]; then overall=FIXED; rc=0
else overall=REVIEW; rc=3
fi
echo "OVERALL: $overall (exit $rc)"
exit $rc
