#!/bin/sh
# Post-pull: strip CRLF and chmod a+x on every EtherGold .sh (recursive).
# Safe without +x: bash pi_normalize.sh

ROOT=$(cd "$(dirname "$0")" && pwd)
# shellcheck source=ethergold_paths.sh
. "${ROOT}/ethergold_paths.sh"
SCAN_ROOT="${ETHERGOLD_ROOT}"

find_sh() {
  find "${SCAN_ROOT}" -type f -name '*.sh' \
    ! -path "${SCAN_ROOT}/_archive/*" \
    "$@"
}

find_sh -exec sh -c '
  for f; do
    [ -f "$f" ] || continue
    tr -d "\r" < "$f" > "$f.tmp" && mv "$f.tmp" "$f"
    chmod a+x "$f" || echo "  WARN chmod failed: $f" >&2
    echo "  +x  $f"
  done
' _ {} +

for f in "$ROOT"/*.rclone-filter; do
  [ -f "$f" ] || continue
  tr -d '\r' < "$f" > "$f.tmp" && mv "$f.tmp" "$f"
done

for f in "$ROOT"/rclone.env "$ROOT"/rclone.env.example; do
  [ -f "$f" ] || continue
  tr -d '\r' < "$f" > "$f.tmp" && mv "$f.tmp" "$f"
done

total=$(find_sh 2>/dev/null | wc -l | tr -d ' ')

echo "pi_normalize: ${total} shell script(s) — LF stripped, chmod a+x (under ${SCAN_ROOT}; excl _archive/)"
