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

# This script is intentionally run on the Synology host, before the canonical
# platform artifact apply. It changes collection policy only; provider
# credentials remain in the protected Engine credential store.
NAS_ROOT="${NAS_ROOT:-/volume1/docker/nodedc-platform}"
PLATFORM_ENV="${PLATFORM_ENV:-${NAS_ROOT}/platform/.env.synology}"
BACKUP_ROOT="${BACKUP_ROOT:-/volume1/docker/nodedc-deploy/backups/gelios-policy}"
TIMESTAMP="${TIMESTAMP:-$(date +%Y%m%d-%H%M%S)}"
BACKUP_DIR="${BACKUP_DIR:-${BACKUP_ROOT}/${TIMESTAMP}}"

read_env() {
  local file="$1"
  local key="$2"
  awk -F= -v key="${key}" '
    $0 ~ "^[[:space:]]*#" { next }
    $1 == key {
      value = substr($0, index($0, "=") + 1)
      gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)
      gsub(/^"|"$/, "", value)
      print value
      exit
    }
  ' "${file}"
}

set_env_value() {
  local file="$1"
  local key="$2"
  local value="$3"
  local tmp
  tmp="$(mktemp "${file}.tmp.XXXXXX")"
  awk -v key="${key}" -v value="${value}" '
    BEGIN { replaced = 0 }
    $0 ~ "^[[:space:]]*#" { print; next }
    index($0, key "=") == 1 {
      print key "=" value
      replaced = 1
      next
    }
    { print }
    END {
      if (!replaced) print key "=" value
    }
  ' "${file}" > "${tmp}"
  chmod 600 "${tmp}"
  mv "${tmp}" "${file}"
}

if [[ ! -f "${PLATFORM_ENV}" ]]; then
  echo "missing Platform env: ${PLATFORM_ENV}" >&2
  exit 1
fi

tenant_id="$(read_env "${PLATFORM_ENV}" GELIOS_TENANT_ID || true)"
connection_id="$(read_env "${PLATFORM_ENV}" GELIOS_CONNECTION_ID || true)"
if [[ -z "${tenant_id}" || -z "${connection_id}" || "${tenant_id}" == replace-with-* || "${connection_id}" == replace-with-* ]]; then
  echo "GELIOS_TENANT_ID and GELIOS_CONNECTION_ID must be configured before enabling all-unit collection" >&2
  exit 1
fi

mkdir -p "${BACKUP_DIR}"
backup_path="${BACKUP_DIR}/platform.env.synology.before-gelios-all-units"
cp "${PLATFORM_ENV}" "${backup_path}"
chmod 600 "${backup_path}"

# `all` is constrained to the one tenant + connection validated above; it is
# not a wildcard across Gelios tenants or other providers. Existing stable
# unit rows are never deleted by this policy.
set_env_value "${PLATFORM_ENV}" GELIOS_UNIT_SCOPE "all"
set_env_value "${PLATFORM_ENV}" GELIOS_INTAKE_ENABLED "true"

cat <<EOF
gelios-all-units-env-prep-ok
backup_path=${backup_path}
updated_platform_env=${PLATFORM_ENV}
unit_scope=all
intake_enabled=true
secrets_printed=false
EOF
