#!/bin/sh
##
## fidsift version 1.00 by Mark Lord
##
## This script can be run on the empeg to automatically
## sift and sort the FIDS into subdirectories to help
## optimise filesystem access for rebuilds and fscks.
##
function dosift() {
	echo "Sifting ${1}.."
	cd "${1}"
	## ensure that at least one file will match
	echo >"000"
	## now move the fids around:
	for fid in [0-9a-f]*; do
		f="00000${fid}"
		f="${f:${#f}-8}"
		d="_${f:0:5}"
		f="${f:5:3}"
		mkdir --verbose -p "${d}" || exit -1
		mv "${fid}" "${d}/${f}" || exit -1
	done
	[ -f "_00000/000" ] && rm -f "_00000/000"
	cd ..
	## Shrink the fids directory itself now:
	mkdir -p nfids
	if [ -d nfids ]; then
		chmod 0755 nfids
		mv fids/* nfids
	fi
	rmdir fids && mv nfids fids
	cd /
}

function dodrive() {
	drive=$1
	if [ -d ${drive}/fids ]; then
		mount -n ${drive} -oremount,rw,nocheck && dosift ${drive}/fids
		mount -n ${drive} -oremount,ro
		sync
	fi
}

## main() {
	echo "$0: version 1.03, by Mark Lord"
	swapon /dev/hda6
	dodrive /drive0
	dodrive /drive1
	swapoff /dev/hda6
	sync
#}
