#!/usr/bin/env bash
# Restore LF for git-tracked files from index; strip CR from untracked *.sh in scripts/
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${ROOT}"

if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "normalize_worktree_lf: not a git repo" >&2
  exit 1
fi

git config core.autocrlf false 2>/dev/null || true

echo "Restoring tracked files from git index (LF)..."
git config core.autocrlf false 2>/dev/null || true
git config core.eol lf 2>/dev/null || true

# git restore 在部分环境下仍会把工作区检出为 CRLF；直接从索引 blob 写盘（LF 真相源）
rewrite_from_index() {
  local n=0
  while IFS= read -r f; do
    [ -n "${f}" ] || continue
    mkdir -p "$(dirname "${f}")"
    git show ":${f}" > "${f}.tmp" && mv -f "${f}.tmp" "${f}"
    n=$((n + 1))
  done
  echo "${n}"
}

echo "Rewriting tracked sources from git index (LF blobs)..."
paths=(
  "server"
  "scripts"
  "deploy"
  "docker"
  "tests"
  "web/agent"
  "frontend/src"
  "frontend/e2e"
  "mcp"
  ".cursor/rules"
)
total=0
for p in "${paths[@]}"; do
  count=$(git ls-files "${p}" 2>/dev/null | rewrite_from_index)
  total=$((total + count))
done
echo "  ${total} file(s) rewritten"

shopt -s nullglob
for f in scripts/*.sh docker/*.sh deploy/*.sh; do
  [ -f "${f}" ] || continue
  if grep -q $'\r' "${f}" 2>/dev/null; then
    sed -i 's/\r$//' "${f}"
    echo "  stripped CR: ${f}"
  fi
done

for f in scripts/proxy-env.sh scripts/with-proxy.sh scripts/linux_mcp_mysql.sh UBUNTU-DEV-README.txt; do
  [ -f "${f}" ] || continue
  if grep -q $'\r' "${f}" 2>/dev/null; then
    sed -i 's/\r$//' "${f}"
    echo "  stripped CR: ${f}"
  fi
done

echo "Done. Verify: python3 scripts/check_worktree_eol.py"
