#!/usr/bin/env bash

strip_log_level_example_block() {
  local file="$1"
  [[ -f "$file" ]] || return 0

  local tmp
  tmp="$(mktemp)"
  awk '
    /^# 日志级别[:：]/ { skip = 1; next }
    skip && /^# / { next }
    skip && /^LOG_LEVEL=/ { skip = 0; next }
    { if (skip) skip = 0; print }
  ' "$file" > "$tmp"
  mv "$tmp" "$file"
}

sanitize_delivery_snapshot() {
  printf '[delivery-snapshot] 清理交付快照中的内部发布信息\n'

  if [[ -f README.md ]]; then
    local readme_tmp
    readme_tmp="$(mktemp)"
    awk '
      /<!-- delivery-internal:start -->/ { skip = 1; next }
      /<!-- delivery-internal:end -->/ { skip = 0; next }
      !skip { print }
    ' README.md > "$readme_tmp"
    mv "$readme_tmp" README.md
  fi

  strip_log_level_example_block README.md
  strip_log_level_example_block .env.example

  if [[ -f package.json ]]; then
    command -v node >/dev/null 2>&1 || {
      printf '[delivery-snapshot] ERROR: 清理 package.json 需要 node\n' >&2
      exit 1
    }
    node <<'EOF'
const fs = require('node:fs');
const packagePath = 'package.json';
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));

if (packageJson.scripts) {
  delete packageJson.scripts['publish:delivery'];
}

fs.writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
EOF
  fi

  rm -f scripts/publish-delivery.sh
}
