#!/bin/bash
# Reap one cargo pool with the IR-150 census. usage: reap.sh <pool-dir> <logfile>
P="$1"; LOG="$2"
W=/c/Users/decid/Documents/projects/spt-core
{
echo "=== reap $P at $(date -u +%FT%TZ)"
echo "--- outbound (LinkType empty = real dir)"
powershell -NoProfile -Command "\$i = Get-Item -Force '$(cygpath -w "$P")'; 'LinkType=' + \$i.LinkType + ' Attributes=' + \$i.Attributes"
echo "--- inbound reparse points under $W aimed at it (depth 3)"
powershell -NoProfile -Command "Get-ChildItem -Path '$(cygpath -w "$W")' -Recurse -Depth 3 -Force -Attributes ReparsePoint -ErrorAction SilentlyContinue | Where-Object { \$_.Target -and (\$_.Target -join ';') -like '*$(basename "$(dirname "$P")")*target*' } | ForEach-Object { \$_.FullName + ' -> ' + (\$_.Target -join ';') }; 'inbound-sweep-done'"
echo "--- three numbers"
APP=$(du -sb --apparent-size "$P" | cut -f1)
ALLOC=$(du -sB1 "$P" | cut -f1)
ESC=$(find "$P" -type f -links +1 -printf '%i %n %s\n' | sort | uniq -c | awk '$1 < $3 { n++; b += $4 } END { print n+0, b+0 }')
echo "apparent=$APP allocated=$ALLOC escaped(inodes bytes)=$ESC"
ESCB=$(echo "$ESC" | awk '{print $2}')
EXPECT=$((ALLOC - ESCB))
echo "expected_reclaim=$EXPECT"
echo "--- writer census"
powershell -NoProfile -Command "Get-CimInstance Win32_Process | Where-Object { \$_.Name -match '^(cargo|cargo-nextest|rustc|link|Runner\.Worker|msbuild|git|spt)\.exe$' } | ForEach-Object { '{0} {1} {2}' -f \$_.ProcessId, \$_.Name, \$_.ExecutablePath }"
F0=$(df -B1 --output=avail /c | tail -1 | tr -d ' ')
echo "free_before=$F0"
rm -rf "$P"; echo "rm rc=$?"
F1=$(df -B1 --output=avail /c | tail -1 | tr -d ' ')
echo "free_after=$F1 delta=$((F1 - F0)) expected=$EXPECT diff=$(( (F1 - F0) - EXPECT ))"
echo "exists_after=$(test -e "$P" && echo yes || echo no)"
} >> "$LOG" 2>&1
