#!/usr/bin/env bash
# ==============================================================================
# ACW-SEDCI cPanel Ecosystem Discovery & Central Vault Policy Rollout Script
# Usage:
#   bash rollout_hub_policy.sh --discover        # Scan cPanel webroots & list portals
#   bash rollout_hub_policy.sh --dry-run         # Preview changes without modifying files
#   bash rollout_hub_policy.sh --apply           # Backup & inject/update shared hub script
# ==============================================================================
set -euo pipefail

MODE="${1:---discover}"
CPANEL_USER="$(whoami)"
HOME_DIR="${HOME:-/home/${CPANEL_USER}}"
HUB_SCRIPT_URL="https://dataroom.acw-sedci.com/assets/js/sedci-hub-client.js"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MANIFEST_FILE="${SCRIPT_DIR}/portals.conf"
BACKUP_ROOT="${HOME_DIR}/private_compliance_storage/rollout_backups/$(date +%Y%m%d_%H%M%S)"

MARKER_START="<!-- ACW-SEDCI-HUB:START -->"
MARKER_END="<!-- ACW-SEDCI-HUB:END -->"

infer_segment_code() {
  local hint="$(echo "$1" | tr '[:upper:]' '[:lower:]')"
  if [[ "$hint" == *"globalblackfarmers"* || "$hint" == *"agro"* || "$hint" == *"food"* ]]; then
    echo "SEG-FSS"
  elif [[ "$hint" == *"mining"* || "$hint" == *"infra"* || "$hint" == *"equipment"* ]]; then
    echo "SEG-INF"
  elif [[ "$hint" == *"logistics"* || "$hint" == *"veda"* || "$hint" == *"piic"* || "$hint" == *"finance"* ]]; then
    echo "SEG-MM"
  elif [[ "$hint" == *"ramitts"* || "$hint" == *"tech"* || "$hint" == *"squad"* ]]; then
    echo "SEG-ST"
  elif [[ "$hint" == *"ubuntu"* || "$hint" == *"social"* || "$hint" == *"diaspora"* ]]; then
    echo "SEG-SR"
  else
    echo "UNGROUPED"
  fi
}

discover_roots() {
  local tmp_list
  tmp_list="$(mktemp)"

  if [[ -d "/var/cpanel/userdata/${CPANEL_USER}" ]]; then
    grep -hE "^documentroot:" "/var/cpanel/userdata/${CPANEL_USER}/"* 2>/dev/null       | awk '{print $2}' >> "$tmp_list" || true
  fi

  for base in "${HOME_DIR}/public_html" "${HOME_DIR}"/*.acw-sedci.com "${HOME_DIR}/subdomains/"*; do
    [[ -d "$base" ]] && echo "$base" >> "$tmp_list"
  done

  if [[ -d "${HOME_DIR}/public_html" ]]; then
    find "${HOME_DIR}/public_html" -maxdepth 2 -type f \( -name "index.html" -o -name "index.php" \) 2>/dev/null       | xargs -r -n1 dirname >> "$tmp_list" || true
  fi

  if [[ -f "$MANIFEST_FILE" ]]; then
    grep -vE '^\s*(#|$)' "$MANIFEST_FILE" | cut -d'|' -f1 >> "$tmp_list" || true
  fi

  sort -u "$tmp_list" | while IFS= read -r dir; do
    [[ -d "$dir" ]] || continue
    [[ "$dir" == *"dataroom"* ]] && continue
    if [[ -f "${dir}/index.html" || -f "${dir}/index.php" ]]; then
      echo "$dir"
    fi
  done
  rm -f "$tmp_list"
}

lookup_manifest_row() {
  local target_dir="$1"
  if [[ -f "$MANIFEST_FILE" ]]; then
    grep -F "${target_dir}|" "$MANIFEST_FILE" | head -n 1 || true
  fi
}

process_portal() {
  local webroot="$1"
  local entry_file=""
  [[ -f "${webroot}/index.html" ]] && entry_file="${webroot}/index.html"
  [[ -z "$entry_file" && -f "${webroot}/index.php" ]] && entry_file="${webroot}/index.php"
  [[ -z "$entry_file" ]] && return 0

  local row portal_id seg_code ag_code
  row="$(lookup_manifest_row "$webroot")"
  if [[ -n "$row" ]]; then
    portal_id="$(echo "$row" | cut -d'|' -f2)"
    seg_code="$(echo "$row" | cut -d'|' -f3)"
    ag_code="$(echo "$row" | cut -d'|' -f4)"
  else
    portal_id="$(basename "$webroot")"
    seg_code="$(infer_segment_code "$webroot")"
    ag_code=""
  fi

  echo "------------------------------------------------------------------"
  echo "Portal Root : ${webroot}"
  echo "Entry File  : ${entry_file}"
  echo "Portal ID   : ${portal_id}"
  echo "Segment     : ${seg_code} (UNGROUPED = non-segment / standalone portal)"
  echo "Agenda      : ${ag_code:-ALL}"

  [[ "$MODE" == "--discover" ]] && return 0

  local seg_attr="" ag_attr=""
  [[ -n "$seg_code" && "$seg_code" != "UNGROUPED" && "$seg_code" != "NONE" ]] && seg_attr=" data-sedci-segment="${seg_code}""
  [[ -n "$ag_code" && "$ag_code" != "NONE" ]] && ag_attr=" data-sedci-agenda="${ag_code}""

  local block="${MARKER_START}
<script src="${HUB_SCRIPT_URL}" defer></script>
<!-- Hub Mount Attributes Available: data-sedci-hub data-sedci-portal="${portal_id}"${seg_attr}${ag_attr} -->
${MARKER_END}"

  if [[ "$MODE" == "--dry-run" ]]; then
    echo "[DRY-RUN] Would ensure shared hub script block is present in ${entry_file}"
    return 0
  fi

  if [[ "$MODE" == "--apply" ]]; then
    mkdir -p "$BACKUP_ROOT"
    local safe_backup_name
    safe_backup_name="$(echo "${entry_file}" | sed 's#[^A-Za-z0-9._-]#_#g')"
    cp -p "$entry_file" "${BACKUP_ROOT}/${safe_backup_name}.bak"

    python3 - "$entry_file" "$MARKER_START" "$MARKER_END" "$block" <<'PYEOF'
import sys, re

path, m_start, m_end, block = sys.argv[1:5]
with open(path, 'r', encoding='utf-8', errors='replace') as f:
    html = f.read()

pattern = re.compile(re.escape(m_start) + r'.*?' + re.escape(m_end), re.DOTALL)
if pattern.search(html):
    new_html = pattern.sub(block, html, count=1)
elif '</body>' in html.lower():
    new_html = re.sub(r'</body>', block + '
</body>', html, count=1, flags=re.IGNORECASE)
else:
    new_html = html + '
' + block + '
'

with open(path, 'w', encoding='utf-8') as f:
    f.write(new_html)
print(f"[APPLIED] Updated {path}")
PYEOF
  fi
}

echo "=== ACW-SEDCI cPanel Portal Discovery & Hub Rollout (${MODE}) ==="
while IFS= read -r root; do
  [[ -n "$root" ]] && process_portal "$root"
done < <(discover_roots)

if [[ "$MODE" == "--apply" ]]; then
  echo "Backups saved under: ${BACKUP_ROOT}"
fi
