#!/usr/bin/env bash
# =============================================================================
# scan-rocketchat-environment.sh
#
# Read-only discovery scan of the current server. Reports everything already
# installed/configured that is relevant to planning a new Rocket.Chat group,
# and inventories any Rocket.Chat groups that already exist on this host.
#
# Writes its findings to ./rocketchat-install-summary (plain text).
# Wherever a discovered value corresponds to a field in
# rocketchat-group-preflight.conf, the SAME variable name is used here, so
# the two files can be compared side by side.
#
# This script makes NO changes to the system — it only reads.
#
# Usage:
#   sudo ./scan-rocketchat-environment.sh
#
# SECURITY NOTE: the "EXISTING ROCKET.CHAT GROUPS" section below includes
# each group's ADMIN_PASSWORD (and MONGO_PASSWORD, if the connection string
# embeds one) in plaintext, because that is how it is already stored in each
# group's own env file. For now, during the build/debug phase, the output
# file is deliberately left world-readable (644) AND ownership is handed to
# the real user who invoked sudo (best effort) - so no matter which local
# account you use to open/download/review it, no chmod/chown step is needed
# on your end. Harden this back down (e.g. chmod 600, root:root, or delete
# after review) once the installer itself is finalized.
# =============================================================================

set -uo pipefail

[[ $EUID -eq 0 ]] || { echo "Run as root (sudo)."; exit 1; }

OUTFILE="./rocketchat-install-summary"
: > "$OUTFILE"

out() { echo "$1" >> "$OUTFILE"; }
section() {
  out ""
  out "-----------------------------------------------------------------------"
  out "$1"
  out "-----------------------------------------------------------------------"
}
kv() { out "${1}=${2}"; }

command_exists() { command -v "$1" &>/dev/null; }

# Returns 0 (true) if version $1 >= version $2, using natural version sort.
version_ge() {
  [[ "$1" == "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n1)" ]]
}

# Extracts the value of KEY from a config file, trying several conventions
# in order, since we don't know in advance which one a given server used:
#   1) Environment="KEY=value"   (quoted, inline in a systemd override.conf)
#   2) Environment=KEY=value     (UNQUOTED, one assignment per line — this
#                                  is the actual format confirmed on this
#                                  host's real override.conf files. The key
#                                  sits directly after "Environment=" with
#                                  no separating space or quote, which the
#                                  older fallback pattern below could not
#                                  match.)
#   3) KEY=value                 (bare, unquoted — typical of a plain
#                                  EnvironmentFile=-referenced .env file)
# Accepts one or two candidate files; checks each in order and returns the
# first match found.
extract_env_value() {
  local var="$1"; shift
  local file val
  for file in "$@"; do
    [[ -n "$file" && -r "$file" ]] || continue

    # Form 1: Environment="KEY=value"
    val="$(grep -oP "(?<=\")${var}=[^\"]*" "$file" 2>/dev/null | head -1 | sed -E "s/^${var}=//")"

    # Form 2: Environment=KEY=value (unquoted, anchored right after the
    # literal "Environment=" prefix so it can't partial-match a different,
    # longer variable name that happens to share a suffix, e.g. PORT vs
    # TCP_PORT).
    if [[ -z "$val" ]]; then
      val="$(grep -oP "^\s*Environment=${var}=\K.*" "$file" 2>/dev/null | tail -1)"
      val="${val%\"}"; val="${val#\"}"
    fi

    # Form 3: bare KEY=value, anchored at line-start or after whitespace
    if [[ -z "$val" ]]; then
      val="$(grep -oP "(^|[[:space:]])${var}=\S*" "$file" 2>/dev/null | tail -1 | sed -E "s/^.*${var}=//")"
    fi

    if [[ -n "$val" ]]; then
      echo "$val"
      return
    fi
  done
  echo ""
}

# Given a systemd override.conf, returns the path referenced by an
# EnvironmentFile= directive inside it, if any (handles the optional
# leading '-' that means "ignore if missing").
extract_environment_file_ref() {
  local file="$1"
  [[ -r "$file" ]] || { echo ""; return; }
  grep -oP '^\s*EnvironmentFile=-?\K\S+' "$file" 2>/dev/null | head -1
}

out "======================================================================="
out " ROCKET.CHAT ENVIRONMENT SCAN — SUMMARY"
out " Generated: $(date '+%Y-%m-%d %H:%M:%S %Z')"
out " Host:      $(hostname)"
out "======================================================================="

# --------------------------------------------------------------------------
section "SYSTEM"
# --------------------------------------------------------------------------
KERNEL_RAW="$(uname -r)"
KERNEL_BASE="${KERNEL_RAW%%-*}"
kv "KERNEL_VERSION" "$KERNEL_RAW"

if [[ -r /etc/os-release ]]; then
  OS_NAME="$(. /etc/os-release; echo "$PRETTY_NAME")"
else
  OS_NAME="unknown"
fi
kv "OS_NAME" "$OS_NAME"
kv "HOSTNAME" "$(hostname)"
kv "SERVER_IP" "$(hostname -I 2>/dev/null | awk '{print $1}')"

# --- Kernel compatibility check for MongoDB (Rocket.Chat's required DB) ----
# Sources:
#  - MongoDB general minimum recommended kernel: 2.6.36
#    https://www.mongodb.com/docs/v8.0/administration/production-notes/
#  - MongoDB 8.0+ known to crash on startup on kernel 6.19+ (TCMalloc
#    incompatibility, unresolved as of MongoDB 8.2 release notes):
#    https://www.mongodb.com/docs/manual/release-notes/8.2/
MONGO_MIN_KERNEL="2.6.36"
MONGO_BREAK_KERNEL="6.19"

if version_ge "$KERNEL_BASE" "$MONGO_BREAK_KERNEL"; then
  KERNEL_STATUS="INCOMPATIBLE — kernel $KERNEL_BASE is at or above 6.19. MongoDB 8.0+ is documented to crash on startup on kernel 6.19+ due to a TCMalloc incompatibility that was still unresolved as of the latest MongoDB release notes. Do not proceed with MongoDB 8.0 on this kernel without checking for a fix, or downgrade the kernel below 6.19."
elif version_ge "$KERNEL_BASE" "$MONGO_MIN_KERNEL"; then
  KERNEL_STATUS="OK — kernel $KERNEL_BASE meets MongoDB's minimum recommended version ($MONGO_MIN_KERNEL+) and is below the known-incompatible 6.19+ threshold for MongoDB 8.0."
  # Proximity warning: flag if within the same major version and close to the break point.
  KERNEL_MAJOR="${KERNEL_BASE%%.*}"
  BREAK_MAJOR="${MONGO_BREAK_KERNEL%%.*}"
  if [[ "$KERNEL_MAJOR" == "$BREAK_MAJOR" ]]; then
    KERNEL_MINOR="$(echo "$KERNEL_BASE" | cut -d. -f2)"
    BREAK_MINOR="$(echo "$MONGO_BREAK_KERNEL" | cut -d. -f2)"
    if (( BREAK_MINOR - KERNEL_MINOR <= 2 )); then
      KERNEL_STATUS="${KERNEL_STATUS} CAUTION: this is close to the 6.19 break point — avoid unattended/automatic kernel upgrades on this host while running MongoDB 8.0, or you may cross that threshold unexpectedly."
    fi
  fi
else
  KERNEL_STATUS="WARNING — kernel $KERNEL_BASE is below MongoDB's minimum recommended version ($MONGO_MIN_KERNEL). Upgrade the kernel before installing MongoDB."
fi
kv "KERNEL_ROCKETCHAT_COMPATIBILITY_STATUS" "$KERNEL_STATUS"

# --------------------------------------------------------------------------
section "NODE.JS"
# --------------------------------------------------------------------------
if command_exists node; then
  kv "NODE_BIN_PATH" "$(command -v node)"
  kv "NODE_VERSION" "$(node -v)"
else
  kv "NODE_BIN_PATH" "NOT FOUND"
  kv "NODE_VERSION" "n/a"
fi

# --------------------------------------------------------------------------
section "APACHE2"
# --------------------------------------------------------------------------
if dpkg -s apache2 &>/dev/null; then
  kv "APACHE_INSTALLED" "yes"
  kv "APACHE_VERSION" "$(apache2 -v 2>/dev/null | head -1)"
  [[ -d /etc/apache2/sites-available ]] && kv "APACHE_SITES_AVAILABLE_DIR" "/etc/apache2/sites-available"
  [[ -d /etc/apache2/sites-enabled ]] && kv "APACHE_SITES_ENABLED_DIR" "/etc/apache2/sites-enabled"
  out "APACHE_ENABLED_MODULES="
  apache2ctl -M 2>/dev/null | awk '{print $1}' | sed 's/_module$//' | while read -r m; do out "  $m"; done
else
  kv "APACHE_INSTALLED" "no"
fi

# --------------------------------------------------------------------------
section "MONGODB"
# --------------------------------------------------------------------------
if command_exists mongod; then
  kv "MONGO_INSTALLED" "yes"
  kv "MONGO_VERSION" "$(mongod --version 2>/dev/null | head -1)"
else
  kv "MONGO_INSTALLED" "no"
fi

MONGO_LISTEN_LINE="$(ss -tlnp 2>/dev/null | grep -i mongod | head -1)"
MONGO_PORT_DETECTED="$(echo "$MONGO_LISTEN_LINE" | grep -oP ':\K[0-9]+(?=\s)' | head -1)"
kv "MONGO_HOST" "localhost"
kv "MONGO_PORT" "${MONGO_PORT_DETECTED:-27017 (assumed default — not confirmed listening)}"

if command_exists mongosh; then
  RS_NAME="$(mongosh --quiet --eval 'try{print(rs.status().set)}catch(e){print("n/a")}' 2>/dev/null)"
  kv "MONGO_REPLICA_SET" "${RS_NAME:-n/a}"

  out "MONGO_DATABASES="
  mongosh --quiet --eval 'db.adminCommand({listDatabases:1}).databases.forEach(d=>print(d.name))' 2>/dev/null \
    | while read -r d; do out "  $d"; done

  AUTH_ENABLED="$(mongosh --quiet --eval 'try{db.getSiblingDB("admin").system.users.countDocuments()>0 ? print("yes") : print("no")}catch(e){print("unknown")}' 2>/dev/null)"

  # Corroborate the live probe above by also checking mongod.conf directly
  # for an active (uncommented) security.authorization setting. If both
  # checks agree that auth is off, that's strong, direct evidence that no
  # MongoDB username/password exists anywhere on this host to report —
  # not a scan failure. If they disagree, flag it for manual review.
  MONGOD_CONF_PATH=""
  for c in /etc/mongod.conf /etc/mongodb.conf; do
    [[ -r "$c" ]] && { MONGOD_CONF_PATH="$c"; break; }
  done
  AUTHZ_CONF_VAL="$(grep -oP '^\s*authorization:\s*\K\S+' "$MONGOD_CONF_PATH" 2>/dev/null | head -1)"
  if [[ -n "$MONGOD_CONF_PATH" ]]; then
    if [[ -z "$AUTHZ_CONF_VAL" ]]; then
      CONF_EVIDENCE="security.authorization is not set in ${MONGOD_CONF_PATH} (commented out/absent = auth disabled)"
    else
      CONF_EVIDENCE="security.authorization: ${AUTHZ_CONF_VAL} in ${MONGOD_CONF_PATH}"
    fi
  else
    CONF_EVIDENCE="mongod.conf not found/readable to cross-check"
  fi
  kv "MONGO_AUTH_ENABLED" "${AUTH_ENABLED:-unknown} (live probe) — ${CONF_EVIDENCE}"

  out "MONGO_DB_USERS_GLOBAL="
  out "  (system-wide MongoDB accounts, usernames only — MongoDB never stores a recoverable plaintext password, so credentials cannot be extracted here; per-group connection credentials, if any, are reported separately below under EXISTING ROCKET.CHAT GROUPS. If MONGO_AUTH_ENABLED above is 'no', there ARE no MongoDB-level credentials on this host at all — Rocket.Chat connects without a username/password, which is expected and secure as long as MongoDB only binds to localhost/private interfaces.)"
  mongosh --quiet --eval 'try{db.getSiblingDB("admin").system.users.find().forEach(u=>print(u.user))}catch(e){}' 2>/dev/null \
    | while read -r u; do out "  $u"; done
else
  kv "MONGO_REPLICA_SET" "n/a (mongosh not found)"
fi

# --------------------------------------------------------------------------
section "SUPPORTING TOOLS"
# --------------------------------------------------------------------------
kv "OPENSSL_VERSION" "$(openssl version 2>/dev/null || echo 'NOT FOUND')"
if command_exists certbot; then
  kv "CERTBOT_INSTALLED" "yes"
  kv "CERTBOT_VERSION" "$(certbot --version 2>/dev/null)"
else
  kv "CERTBOT_INSTALLED" "no"
fi
kv "BUILD_ESSENTIAL_INSTALLED" "$(dpkg -s build-essential &>/dev/null && echo yes || echo no)"
kv "PYTHON3_INSTALLED" "$(command_exists python3 && echo yes || echo no)"

# --------------------------------------------------------------------------
section "PORTS CURRENTLY LISTENING (ALL SERVICES ON THIS HOST)"
# --------------------------------------------------------------------------
out "LISTENING_PORTS="
out "$(printf '  %-6s %-8s %s' PROTO PORT PROCESS)"
while IFS= read -r line; do
  [[ "$line" =~ ^(tcp|udp) ]] || continue
  proto="$(awk '{print $1}' <<< "$line")"
  laddr="$(awk '{print $5}' <<< "$line")"
  port="${laddr##*:}"
  if [[ "$line" =~ \(\(\"([^\"]+)\" ]]; then
    pname="${BASH_REMATCH[1]}"
  else
    pname="n/a (run with sudo to see process names)"
  fi
  out "$(printf '  %-6s %-8s %s' "$proto" "$port" "$pname")"
done < <(ss -tulnp 2>/dev/null | tail -n +2)

# Fallback raw dump in case the parsing above doesn't line up cleanly
# on this system's ss output format:
out ""
out "  (raw ss -tulnp output, for cross-reference if the columns above look off)"
while IFS= read -r line; do out "  $line"; done < <(ss -tulnp 2>/dev/null)

# --------------------------------------------------------------------------
# EXISTING ROCKET.CHAT GROUPS — discover + parse config files
# --------------------------------------------------------------------------

declare -a UNIT_NAMES=()

while IFS= read -r u; do
  [[ -n "$u" ]] && UNIT_NAMES+=("$u")
done < <(systemctl list-unit-files 'rocketchat.service' --no-legend 2>/dev/null | awk '{print $1}')

while IFS= read -r u; do
  [[ -n "$u" ]] && UNIT_NAMES+=("$u")
done < <(systemctl list-unit-files 'rocketchat-*.service' --no-legend 2>/dev/null | awk '{print $1}')

while IFS= read -r u; do
  [[ -n "$u" ]] && UNIT_NAMES+=("$u")
done < <(systemctl list-units 'rocketchat@*.service' --all --no-legend 2>/dev/null | awk '{print $1}')

mapfile -t UNIT_NAMES < <(printf '%s\n' "${UNIT_NAMES[@]}" | sort -u | grep -v '^$')

# Parallel arrays holding parsed data for each discovered group, so the same
# data can be reused across two separate output sections further down.
declare -a G_UNIT=() G_GROUP_NAME=() G_DOMAIN=() G_APP_PORT=() G_TRANSPORTER_PORT=()
declare -a G_MONGO_HOST=() G_MONGO_PORT=() G_MONGO_DB=() G_MONGO_RS=()
declare -a G_MONGO_USER=() G_MONGO_PASSWORD=()
declare -a G_ADMIN_USER=() G_ADMIN_PASS=() G_ADMIN_EMAIL=()
declare -a G_SERVICE_USER=() G_NODE_BIN=() G_SERVICE_ACTIVE=()
declare -a G_VHOST_FILE=() G_HTTP_PORT=() G_HTTPS_PORT=()
declare -a G_CERT_PATH=() G_KEY_PATH=() G_CERT_NOT_BEFORE=() G_CERT_NOT_AFTER=()
declare -a G_CERT_HAS_SAN=() G_DEPLOY_MODE=()
declare -a G_OVERRIDE_FILE=() G_ENVFILE_REF=()

for UNIT in "${UNIT_NAMES[@]}"; do
  BASE_NAME="${UNIT%.service}"
  INSTANCE_NAME="${BASE_NAME#*@}"

  # Primary candidate: a systemd drop-in override.conf for this unit.
  OVERRIDE_FILE="/etc/systemd/system/${BASE_NAME}.service.d/override.conf"
  [[ -r "$OVERRIDE_FILE" ]] || OVERRIDE_FILE=""

  # Secondary candidate: a plain .env file referenced from the override via
  # EnvironmentFile=, since that's a common alternative convention where the
  # actual KEY=value pairs live in a separate unquoted file.
  ENVFILE_REF=""
  [[ -n "$OVERRIDE_FILE" ]] && ENVFILE_REF="$(extract_environment_file_ref "$OVERRIDE_FILE")"
  [[ -n "$ENVFILE_REF" && -r "$ENVFILE_REF" ]] || ENVFILE_REF=""

  # Also try the naming convention explored earlier in this project, in case
  # no EnvironmentFile= directive is present but a matching file still exists.
  if [[ -z "$ENVFILE_REF" ]]; then
    for guess in "/etc/rocketchat/groups/${INSTANCE_NAME}.env" "/etc/default/${BASE_NAME}" "/etc/${BASE_NAME}.env"; do
      [[ -r "$guess" ]] && { ENVFILE_REF="$guess"; break; }
    done
  fi

  PORT_VAL="" ROOT_URL_VAL="" MONGO_URL_VAL="" TCP_PORT_VAL=""
  ADMIN_USERNAME_VAL="" ADMIN_PASS_VAL="" ADMIN_EMAIL_VAL=""
  DOMAIN_NAME_VAL="" MONGO_HOST_VAL="" MONGO_PORT_VAL="" MONGO_DB_NAME_VAL=""
  MONGO_RS_VAL="" MONGO_USER_VAL="" MONGO_PASSWORD_VAL="" DEPLOY_MODE_VAL="unknown"

  if [[ -n "$OVERRIDE_FILE" || -n "$ENVFILE_REF" ]]; then
    PORT_VAL="$(extract_env_value "PORT" "$OVERRIDE_FILE" "$ENVFILE_REF")"
    ROOT_URL_VAL="$(extract_env_value "ROOT_URL" "$OVERRIDE_FILE" "$ENVFILE_REF")"
    MONGO_URL_VAL="$(extract_env_value "MONGO_URL" "$OVERRIDE_FILE" "$ENVFILE_REF")"
    TCP_PORT_VAL="$(extract_env_value "TCP_PORT" "$OVERRIDE_FILE" "$ENVFILE_REF")"
    ADMIN_USERNAME_VAL="$(extract_env_value "ADMIN_USERNAME" "$OVERRIDE_FILE" "$ENVFILE_REF")"
    ADMIN_PASS_VAL="$(extract_env_value "ADMIN_PASS" "$OVERRIDE_FILE" "$ENVFILE_REF")"
    ADMIN_EMAIL_VAL="$(extract_env_value "ADMIN_EMAIL" "$OVERRIDE_FILE" "$ENVFILE_REF")"

    DOMAIN_NAME_VAL="${ROOT_URL_VAL#https://}"
    DOMAIN_NAME_VAL="${DOMAIN_NAME_VAL#http://}"
    DOMAIN_NAME_VAL="${DOMAIN_NAME_VAL%%/*}"

    # --- local vs. remote deployment classification --------------------
    # Matches the DEPLOY_MODE field in rocketchat-group-preflight.conf
    # ("Must be exactly 'local' or 'remote'"). Computed here from the
    # domain itself, so it's available even before any Apache vhost/TLS
    # cert exists for the group. A stronger, cert-based confirmation is
    # layered on further below if a vhost is already configured.
    if [[ -n "$DOMAIN_NAME_VAL" ]]; then
      case "$DOMAIN_NAME_VAL" in
        *.local|*.lan|*.internal|*.home.arpa|*.test|*.localhost|*.invalid)
          DEPLOY_MODE_VAL="local (domain uses the non-public suffix .${DOMAIN_NAME_VAL##*.}, reserved for internal/LAN use)"
          ;;
        *)
          RESOLVED_IP_VAL="$(timeout 2 getent ahosts "$DOMAIN_NAME_VAL" 2>/dev/null | awk '{print $1}' | head -1)"
          if [[ -z "$RESOLVED_IP_VAL" ]]; then
            DEPLOY_MODE_VAL="local (domain '${DOMAIN_NAME_VAL}' does not resolve via DNS/hosts, so it isn't reachable under this name from the public internet)"
          elif [[ "$RESOLVED_IP_VAL" =~ ^(127\.|10\.|192\.168\.|169\.254\.) || "$RESOLVED_IP_VAL" =~ ^172\.(1[6-9]|2[0-9]|3[0-1])\. ]]; then
            DEPLOY_MODE_VAL="local (domain resolves to a private/loopback address: ${RESOLVED_IP_VAL})"
          else
            DEPLOY_MODE_VAL="remote (domain resolves publicly to ${RESOLVED_IP_VAL})"
          fi
          ;;
      esac
    fi

    # Parse MONGO_URL, with or without embedded credentials:
    #   mongodb://user:pass@host:port/dbname?replicaSet=name
    #   mongodb://host:port/dbname?replicaSet=name
    if [[ "$MONGO_URL_VAL" =~ ^mongodb://([^:/@]+):([^@]+)@([^/:,]+):?([0-9]*)/([^?]+) ]]; then
      MONGO_USER_VAL="${BASH_REMATCH[1]}"
      MONGO_PASSWORD_VAL="${BASH_REMATCH[2]}"
      MONGO_HOST_VAL="${BASH_REMATCH[3]}"
      MONGO_PORT_VAL="${BASH_REMATCH[4]:-27017}"
      MONGO_DB_NAME_VAL="${BASH_REMATCH[5]}"
    elif [[ "$MONGO_URL_VAL" =~ ^mongodb://([^/:,]+):?([0-9]*)/([^?]+) ]]; then
      MONGO_HOST_VAL="${BASH_REMATCH[1]}"
      MONGO_PORT_VAL="${BASH_REMATCH[2]:-27017}"
      MONGO_DB_NAME_VAL="${BASH_REMATCH[3]}"
      MONGO_USER_VAL="(none — no credentials in connection string; matches MONGO_AUTH_ENABLED=no detected above)"
      MONGO_PASSWORD_VAL="(none — no credentials in connection string; matches MONGO_AUTH_ENABLED=no detected above)"
    fi
    if [[ "$MONGO_URL_VAL" =~ replicaSet=([^&]+) ]]; then
      MONGO_RS_VAL="${BASH_REMATCH[1]}"
    fi
  fi

  GROUP_NAME_VAL="${INSTANCE_NAME:-$BASE_NAME}"
  SERVICE_USER_VAL="$(systemctl show "$UNIT" -p User --value 2>/dev/null)"
  NODE_BIN_VAL="$(systemctl show "$UNIT" -p ExecStart --value 2>/dev/null | grep -oP '(?<=path=)\S+' | head -1)"
  SERVICE_ACTIVE_VAL="$(systemctl is-active "$UNIT" 2>/dev/null)"

  VHOST_FILE_VAL="" HTTP_PORT_VAL="" HTTPS_PORT_VAL=""
  CERT_PATH_VAL="" KEY_PATH_VAL="" CERT_NOT_BEFORE_VAL="" CERT_NOT_AFTER_VAL=""
  CERT_HAS_SAN_VAL=""

  if [[ -n "$DOMAIN_NAME_VAL" && -d /etc/apache2/sites-available ]]; then
    VHOST_FILE_VAL="$(grep -rlP "ServerName\s+${DOMAIN_NAME_VAL}\b" /etc/apache2/sites-available/ 2>/dev/null | head -1)"
    if [[ -n "$VHOST_FILE_VAL" ]]; then
      # Walk the vhost file to associate each <VirtualHost *:PORT> block with
      # whether it's the plain-HTTP or SSL-enabled block.
      CURRENT_PORT="" SSL_FLAG=0
      while IFS= read -r vline; do
        if [[ "$vline" =~ \<VirtualHost[[:space:]]+\*:([0-9]+)\> ]]; then
          CURRENT_PORT="${BASH_REMATCH[1]}"
          SSL_FLAG=0
        elif [[ "$vline" =~ SSLEngine[[:space:]]+on ]]; then
          SSL_FLAG=1
        elif [[ "$vline" =~ \</VirtualHost\> ]]; then
          if [[ "$SSL_FLAG" -eq 1 ]]; then
            HTTPS_PORT_VAL="$CURRENT_PORT"
          else
            HTTP_PORT_VAL="$CURRENT_PORT"
          fi
        fi
      done < "$VHOST_FILE_VAL"

      CERT_PATH_VAL="$(grep -oP '^\s*SSLCertificateFile\s+\K.*' "$VHOST_FILE_VAL" 2>/dev/null | head -1)"
      KEY_PATH_VAL="$(grep -oP '^\s*SSLCertificateKeyFile\s+\K.*' "$VHOST_FILE_VAL" 2>/dev/null | head -1)"

      if [[ -n "$CERT_PATH_VAL" && -r "$CERT_PATH_VAL" ]]; then
        CERT_TEXT="$(openssl x509 -in "$CERT_PATH_VAL" -noout -dates -ext subjectAltName 2>/dev/null)"
        CERT_NOT_BEFORE_VAL="$(echo "$CERT_TEXT" | grep -oP 'notBefore=\K.*')"
        CERT_NOT_AFTER_VAL="$(echo "$CERT_TEXT" | grep -oP 'notAfter=\K.*')"
        CERT_HAS_SAN_VAL="no"
        echo "$CERT_TEXT" | grep -q "Subject Alternative Name" && CERT_HAS_SAN_VAL="yes"
      fi

      # Stronger evidence than the domain-only guess above: an actual TLS
      # certificate already in use for this group confirms the mode.
      if [[ -d "/etc/letsencrypt/live/${DOMAIN_NAME_VAL}" ]]; then
        DEPLOY_MODE_VAL="remote (confirmed via Let's Encrypt cert at /etc/letsencrypt/live/${DOMAIN_NAME_VAL})"
      elif [[ -n "$CERT_PATH_VAL" ]]; then
        DEPLOY_MODE_VAL="local (confirmed via self-signed certificate at ${CERT_PATH_VAL})"
      fi
    fi
  fi

  G_UNIT+=("$UNIT")
  G_OVERRIDE_FILE+=("$OVERRIDE_FILE")
  G_ENVFILE_REF+=("$ENVFILE_REF")
  G_GROUP_NAME+=("$GROUP_NAME_VAL")
  G_DOMAIN+=("$DOMAIN_NAME_VAL")
  G_APP_PORT+=("$PORT_VAL")
  G_TRANSPORTER_PORT+=("$TCP_PORT_VAL")
  G_MONGO_HOST+=("$MONGO_HOST_VAL")
  G_MONGO_PORT+=("$MONGO_PORT_VAL")
  G_MONGO_DB+=("$MONGO_DB_NAME_VAL")
  G_MONGO_RS+=("$MONGO_RS_VAL")
  G_MONGO_USER+=("$MONGO_USER_VAL")
  G_MONGO_PASSWORD+=("$MONGO_PASSWORD_VAL")
  G_ADMIN_USER+=("$ADMIN_USERNAME_VAL")
  G_ADMIN_PASS+=("$ADMIN_PASS_VAL")
  G_ADMIN_EMAIL+=("$ADMIN_EMAIL_VAL")
  G_SERVICE_USER+=("$SERVICE_USER_VAL")
  G_NODE_BIN+=("$NODE_BIN_VAL")
  G_SERVICE_ACTIVE+=("$SERVICE_ACTIVE_VAL")
  G_VHOST_FILE+=("$VHOST_FILE_VAL")
  G_HTTP_PORT+=("$HTTP_PORT_VAL")
  G_HTTPS_PORT+=("$HTTPS_PORT_VAL")
  G_CERT_PATH+=("$CERT_PATH_VAL")
  G_KEY_PATH+=("$KEY_PATH_VAL")
  G_CERT_NOT_BEFORE+=("$CERT_NOT_BEFORE_VAL")
  G_CERT_NOT_AFTER+=("$CERT_NOT_AFTER_VAL")
  G_CERT_HAS_SAN+=("$CERT_HAS_SAN_VAL")
  G_DEPLOY_MODE+=("$DEPLOY_MODE_VAL")
done

# --------------------------------------------------------------------------
section "ROCKET.CHAT ASSIGNED PORTS (from config files, not the general port scan)"
# --------------------------------------------------------------------------
if [[ ${#G_UNIT[@]} -eq 0 ]]; then
  out "No Rocket.Chat groups found — nothing to report."
else
  out "ROCKETCHAT_ASSIGNED_PORTS="
  for i in "${!G_UNIT[@]}"; do
    gname="${G_GROUP_NAME[$i]}"
    out "  ${gname}_APP_PORT=${G_APP_PORT[$i]:-unknown}"
    out "  ${gname}_TRANSPORTER_PORT=${G_TRANSPORTER_PORT[$i]:-unknown}"
    out "  ${gname}_HTTP_PORT=${G_HTTP_PORT[$i]:-unknown}"
    out "  ${gname}_HTTPS_PORT=${G_HTTPS_PORT[$i]:-unknown}"
    out "  ${gname}_MONGO_PORT=${G_MONGO_PORT[$i]:-unknown}"
  done
fi

# --------------------------------------------------------------------------
section "EXISTING ROCKET.CHAT GROUPS"
# --------------------------------------------------------------------------
if [[ ${#G_UNIT[@]} -eq 0 ]]; then
  out "No Rocket.Chat systemd units found on this host."
else
  out "GROUPS_FOUND=${#G_UNIT[@]}"
  for i in "${!G_UNIT[@]}"; do
    out ""
    out "[Group $((i + 1)) — unit: ${G_UNIT[$i]}]"
    out "  OVERRIDE_FILE_PATH=${G_OVERRIDE_FILE[$i]:-NOT FOUND}"
    out "  ENVIRONMENT_FILE_PATH=${G_ENVFILE_REF[$i]:-NOT FOUND (no EnvironmentFile= reference and no matching file at known conventions)}"
    if [[ -n "${G_OVERRIDE_FILE[$i]}" ]]; then
      out "  OVERRIDE_FILE_RAW_CONTENT="
      while IFS= read -r rline; do out "    $rline"; done < "${G_OVERRIDE_FILE[$i]}"
    fi
    if [[ -n "${G_ENVFILE_REF[$i]}" ]]; then
      out "  ENVIRONMENT_FILE_RAW_CONTENT="
      while IFS= read -r rline; do out "    $rline"; done < "${G_ENVFILE_REF[$i]}"
    fi
    out "  GROUP_NAME=${G_GROUP_NAME[$i]}"
    out "  DOMAIN_NAME=${G_DOMAIN[$i]:-unknown}"
    out "  DEPLOY_MODE=${G_DEPLOY_MODE[$i]:-unknown}   # matches rocketchat-group-preflight.conf; local = LAN/internal-only, remote = publicly hosted"
    out "  APP_PORT=${G_APP_PORT[$i]:-unknown}"
    out "  TRANSPORTER_PORT=${G_TRANSPORTER_PORT[$i]:-unknown}"
    out "  MONGO_HOST=${G_MONGO_HOST[$i]:-unknown}"
    out "  MONGO_PORT=${G_MONGO_PORT[$i]:-unknown}"
    out "  MONGO_DB_NAME=${G_MONGO_DB[$i]:-unknown}"
    out "  MONGO_REPLICA_SET=${G_MONGO_RS[$i]:-unknown}"
    MONGO_USER_OUT="${G_MONGO_USER[$i]:-unknown}"
    MONGO_PASS_OUT="${G_MONGO_PASSWORD[$i]:-unknown}"
    if [[ "$MONGO_USER_OUT" == \(none* ]]; then
      out "  MONGO_USER=${MONGO_USER_OUT}"
      out "  MONGO_PASSWORD=${MONGO_PASS_OUT}"
    else
      out "  MONGO_USER=${MONGO_USER_OUT}"
      out "  MONGO_PASSWORD=${MONGO_PASS_OUT}   # SENSITIVE — see security note at top of this script"
    fi
    out "  ADMIN_USERNAME=${G_ADMIN_USER[$i]:-unknown}"
    out "  ADMIN_PASSWORD=${G_ADMIN_PASS[$i]:-unknown}   # SENSITIVE — see security note at top of this script"
    out "  ADMIN_EMAIL=${G_ADMIN_EMAIL[$i]:-unknown}"
    out "  SERVICE_USER=${G_SERVICE_USER[$i]:-unknown}"
    out "  NODE_BIN_PATH=${G_NODE_BIN[$i]:-unknown}"
    out "  SERVICE_ACTIVE=${G_SERVICE_ACTIVE[$i]:-unknown}"
    if [[ -n "${G_VHOST_FILE[$i]}" ]]; then
      out "  APACHE_VHOST_FILE=${G_VHOST_FILE[$i]}"
      out "  HTTP_PORT=${G_HTTP_PORT[$i]:-unknown}"
      out "  HTTPS_PORT=${G_HTTPS_PORT[$i]:-unknown}"
      out "  EXISTING_CERT_PATH=${G_CERT_PATH[$i]:-n/a}"
      out "  EXISTING_KEY_PATH=${G_KEY_PATH[$i]:-n/a}"
      out "  CERT_NOT_BEFORE=${G_CERT_NOT_BEFORE[$i]:-n/a}"
      out "  CERT_NOT_AFTER=${G_CERT_NOT_AFTER[$i]:-n/a}"
      out "  CERT_HAS_SAN=${G_CERT_HAS_SAN[$i]:-n/a}"
    else
      out "  APACHE_VHOST_FILE=NOT FOUND (no vhost matches ServerName ${G_DOMAIN[$i]:-<unknown domain>})"
    fi
  done
fi

out ""
out "======================================================================="
out " END OF SCAN"
out "======================================================================="

# --------------------------------------------------------------------------
# Output file ownership/permissions.
#
# Per explicit instruction: this is a local machine with no security
# concerns, so skip the directory-traversal safety-net/home-directory-copy
# complexity entirely and just make the file fully accessible (rw for
# everyone) to the standard Linux user, no UID-matching required.
# --------------------------------------------------------------------------
REAL_USER="${SUDO_USER:-$(logname 2>/dev/null || echo root)}"
REAL_GROUP="$(id -gn "$REAL_USER" 2>/dev/null || echo "$REAL_USER")"
chown "${REAL_USER}:${REAL_GROUP}" "$OUTFILE" 2>/dev/null || true
chmod 666 "$OUTFILE"

echo "Scan complete. Summary written to: $OUTFILE"
echo "(owner: ${REAL_USER}, permissions 666/fully read-write for any local account — contains plaintext admin/db passwords for any existing groups; this machine was flagged as local-only with no security concerns, so no further hardening is applied automatically)"
