#!/bin/bash

# Declare arrays
declare -a DEV HD OTH FIND

# Check commandline
if [ -z "$2" ]; then
	echo Usage: $0 findparams findcriteria
	echo e.g. $0 -name foo
	exit 1
fi

# Get a list of devices and mountpoints to run find on
devs=0
for a in $(mount -tnonfs,noproc,nodevpts,nodevfs | cut -f1,3 -d' ' | grep -v none | tr ' ' '&'); do
	DEV[$devs]=$(echo $a | tr '&' ' ')
	devs=$(($devs+1))
done

# Substitute real devicename for /dev/root
i=0
while [ $i -lt $devs ]; do
	if [ -n "$(echo ${DEV[$i]} | grep /dev/root)" ]; then
		DEVROOT=$(ls -l /dev/root | cut -f2 -d'>' | tr -d ' ')
		if [ -z $(echo $DEVROOT | grep /dev/) ]; then
			DEVROOT=/dev/$DEVROOT
		fi
		DEV[$i]=$(echo $DEVROOT /)
	fi
	i=$(($i+1))
done

# Break down devices into HDDs and other devices so we can work on partitions
i=0
hds=0
oths=0
while [ $i -lt $devs ]; do
	if [ -n "$(echo ${DEV[$i]} | grep /dev/[sh]d)" ]; then
		HD[$hds]=${DEV[$i]}
		hds=$(($hds+1))	
	else
		OTH[$oths]=${DEV[$i]}
		oths=$(($oths+1))
	fi
	i=$(($i+1))
done

# Now work out what we can parallelise and work out how to parallelise it
# Nb. DEV is reused as we nolonger need it
i=0
finds=0
FIND[0]=
DEV[0]=""
while [ $i -lt $hds ]; do
	devp=$(echo ${HD[$i]} | cut -f1 -d' ') # device with partition
	mp=$(echo ${HD[$i]} | cut -f2 -d' ')   # mountpoint
	devr=$(echo $devp | tr -d 0-9)         # device (whole drive)
	j=0
	added=0
	while [ $j -lt $finds ]; do
		if [ -z "$(echo ${DEV[$j]} | grep $devr)" ]; then
			DEV[$j]="${DEV[$j]} $devr"
			FIND[$j]="${FIND[$j]} $mp"
			added=1
			break
		fi
		j=$(($j+1))
	done
	if [ $added = 0 ]; then
		DEV[$finds]=$devr
		FIND[$finds]=$mp
		finds=$(($finds+1))
	fi		
	i=$(($i+1))
done
i=0
while [ $i -lt $oths ]; do
	FIND[0]="${FIND[0]} $(echo ${OTH[$i]} | cut -f2 -d' ')"
	i=$(($i+1))
done

# Now do the actual work
rm -rf /tmp/out.parallelfind 1>/dev/null 2>/dev/null
rm -rf /tmp/parallelfind* 1>/dev/null 2>/dev/null
i=0
while [ $i -lt $finds ]; do
	count=0
	for a in ${FIND[$i]}; do
		echo $a >>/tmp/flog
		find $a -xdev $@ -print >/tmp/parallelfind$count &
		count=$(($count+1))
	done
	wait
	cat /tmp/parallelfind* >>/tmp/out.parallelfind
	rm /tmp/parallelfind* 1>/dev/null 2>/dev/null
	i=$(($i+1))
done
cat /tmp/out.parallelfind
rm /tmp/out.parallelfind 1>/dev/null 2>/dev/null
