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

NAS_ROOT="${NAS_ROOT:-/Volumes/docker/nodedc-platform}"
PLATFORM_ENV="${PLATFORM_ENV:-${NAS_ROOT}/platform/.env.synology}"
GATEWAY_ENV="${GATEWAY_ENV:-${NAS_ROOT}/ops-agents/.env}"
BACKUP_ROOT="${BACKUP_ROOT:-${NAS_ROOT}/backups/env-prep}"
TIMESTAMP="${TIMESTAMP:-$(date +%Y%m%d-%H%M%S)}"
BACKUP_DIR="${BACKUP_DIR:-${BACKUP_ROOT}/${TIMESTAMP}}"

mkdir -p "${BACKUP_DIR}"

read_env() {
  local file="$1"
  local key="$2"
  [[ -f "${file}" ]] || return 0
  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}"
}

backup_file() {
  local file="$1"
  local label="$2"
  if [[ ! -f "${file}" ]]; then
    echo "missing ${label}: ${file}" >&2
    exit 1
  fi
  local backup_path="${BACKUP_DIR}/$(basename "${file}").${label}.bak"
  if ! COPYFILE_DISABLE=1 cp -X "${file}" "${backup_path}" 2>/dev/null; then
    cat "${file}" > "${backup_path}"
  fi
  chmod 600 "${backup_path}"
}

set_env_value() {
  local file="$1"
  local key="$2"
  local value="$3"
  local tmp
  tmp="$(mktemp)"
  if grep -qE "^${key}=" "${file}"; then
    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}"
  else
    cat "${file}" > "${tmp}"
    printf '\n%s=%s\n' "${key}" "${value}" >> "${tmp}"
  fi
  cat "${tmp}" > "${file}"
  rm -f "${tmp}"
  chmod 600 "${file}"
}

gateway_internal_token="$(read_env "${GATEWAY_ENV}" NODEDC_AGENT_GATEWAY_INTERNAL_TOKEN || true)"
if [[ -z "${gateway_internal_token}" || "${gateway_internal_token}" == replace-with-* || "${gateway_internal_token}" == change-me-* ]]; then
  echo "Gateway NODEDC_AGENT_GATEWAY_INTERNAL_TOKEN is missing or placeholder in ${GATEWAY_ENV}" >&2
  exit 1
fi

backup_file "${PLATFORM_ENV}" platform
backup_file "${GATEWAY_ENV}" ops-agents

set_env_value "${PLATFORM_ENV}" AI_WORKSPACE_HUB_PUBLIC_URL "wss://ai-hub.nodedc.ru/api/ai-workspace/hub"
set_env_value "${PLATFORM_ENV}" AI_WORKSPACE_HUB_INTERNAL_URL "https://ai-hub.nodedc.ru"
set_env_value "${PLATFORM_ENV}" AI_WORKSPACE_HUB_FALLBACK_URLS ""
set_env_value "${PLATFORM_ENV}" AI_WORKSPACE_OPS_ENTITLEMENT_URL "http://172.22.0.222:18190/api/internal/v1/ai-workspace/entitlements"
set_env_value "${PLATFORM_ENV}" AI_WORKSPACE_OPS_ENTITLEMENT_TOKEN "${gateway_internal_token}"
set_env_value "${PLATFORM_ENV}" AI_WORKSPACE_OPS_ENTITLEMENT_REQUIRED "false"

set_env_value "${GATEWAY_ENV}" NODEDC_AI_WORKSPACE_RUN_TOKEN_TTL_SECONDS "43200"

cat <<EOF
ai-workspace-env-prep-ok
backup_dir=${BACKUP_DIR}
updated_platform_env=${PLATFORM_ENV}
updated_gateway_env=${GATEWAY_ENV}
secrets_printed=false
EOF
