#!/bin/sh
#
# cix_collect_xattr.sh
#
# Linux-side collector for the CIXSTA CREATOR/xattr test.
#
# Run as root after CIXSTA.BAT/PART2 and before CIXZIP.BAT:
#   sudo ./cix_collect_xattr.sh
#
# The output names intentionally use DOS/ZIP-safe 8.3 names because the
# DOS-side ZIP step may truncate long names in F:\CIXCMP\LINUX.
#

set -eu

SYS=${SYS:-/var/mars_nwe/SYS}
TREE=${TREE:-$SYS/CIXTEST}
OUT=${OUT:-$SYS/CIXCMP/LINUX}

mkdir -p "$OUT"

INFO="$OUT/collecto.txt"
FILES="$OUT/files.txt"
STAT="$OUT/stat.txt"
XATTR_NAMES="$OUT/xattr_na.txt"
GETFATTR="$OUT/getfattr.txt"
XATTR_FOCUS="$OUT/xattr_fo.txt"

{
  echo "CIX CREATOR xattr/stat collection"
  echo "Created: $(date)"
  echo "Tree: $TREE"
  echo "Output: $OUT"
  echo
} > "$INFO"

if ! command -v getfattr >/dev/null 2>&1; then
  echo "ERROR: getfattr not installed. Install the attr package." | tee "$OUT/getfattr_missing.txt"
  exit 1
fi

if [ ! -d "$TREE" ]; then
  echo "ERROR: test tree not found: $TREE" | tee "$OUT/tree_missing.txt"
  exit 1
fi

find "$TREE" -xdev -print | sort > "$FILES"

{
  echo "path|uid|gid|mode|size|mtime|ctime|atime"
  while IFS= read -r p; do
    stat -c '%n|%u|%g|%a|%s|%y|%z|%x' "$p"
  done < "$FILES"
} > "$STAT"

{
  while IFS= read -r p; do
    echo "### $p"
    getfattr -m - --absolute-names "$p" 2>/dev/null || true
    echo
  done < "$FILES"
} > "$XATTR_NAMES"

{
  while IFS= read -r p; do
    echo "### $p"
    getfattr -d -m - -e hex --absolute-names "$p" 2>/dev/null || true
    echo
  done < "$FILES"
} > "$GETFATTR"

grep -iE 'mars|nwe|netware|trust|owner|creator|modifier|archiv|fileinfo|dos|attr' \
  "$GETFATTR" > "$XATTR_FOCUS" || true

chmod -R a+r "$OUT"

cat <<EOF2
Wrote:
  $INFO
  $FILES
  $STAT
  $XATTR_NAMES
  $GETFATTR
  $XATTR_FOCUS
EOF2
