#!/bin/sh
# $Id: hdinfo.sh,v 1.1 1998/12/30 19:53:05 danw Exp $ 
# Gather information about hard disks on the system.

# Files created:
#	/tmp/netbsdpart		NetBSD partitions (disk, start, size)
#	/tmp/freespace		Free areas (disk, start, size)

min=20480			# Minimum size of an interesting empty space
alldisks="wd0 wd1 sd0 sd1 sd2"	# Supported disk devices

# Find configured disks
for i in $alldisks; do
	fdisk -S $i > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		disks="$disks $i"
	fi
done

# Find all disks with a NetBSD partition.
for i in $disks; do
	PART0ID=0 PART1ID=0 PART2ID=0 PART3ID=0
	PART0START=0 PART0SIZE=0
	PART1START=0 PART1SIZE=0
	PART2START=0 PART2SIZE=0
	PART3START=0 PART3SIZE=0
	eval `fdisk -S /dev/r${i}d 2> /dev/null` 
	for j in 0 1 2 3; do
		eval id='$PART'${j}ID
		if [ "$id" -eq 165 ]; then
			eval echo $i '$PART'${j}START '$PART'${j}SIZE
		fi
	done
done > /tmp/netbsdpart 

# Scan fdisk output and compute empty sections of disks.
for i in $disks; do
	fdisk -S /dev/r${i}d 2>/dev/null | awk -v disk="$i" -v min="$min" -F= '
		BEGIN		{ n = 0; }
		/DLCYL/		{ cyl = $2 }
		/DLHEAD/	{ heads = $2 }
		/DLSEC/		{ sect = $2 }
		# This bit depends on "PARTnSIZE" coming before "PARTnSTART"
		/PART.SIZE/	{ size[n] = $2 }  
		/PART.START/	{ start[n] = $2 ; n++ }
		END {
			if (n >= 4)
				exit 0;

			# Sort gathered information by starting sector.
			for (i = 1; i < n; i++) {
				tstart = start[i];
				tsize = size[i];
				for (j = i - 1; j >= 0; j--) {
					if (tstart > start[j])
						break;
					start[j + 1] = start[j];
					size[j + 1] = size[j];
				}
				start[j + 1] = tstart;
				size[j + 1] = tsize;
			}

			# Output list of free sections.
			csect=sect - 1;
			for (i in start) {
				if (start[i] - csect >= min)
					print disk, csect, start[i] - csect;
				if (csect < start[i] + size[i])
					csect = start[i] + size[i];
			}
			total = cyl * heads * sect;
			if (total - csect >= min)
				print disk, csect, total - csect;
		}' 
done > /tmp/freespace

if [ ! -s /tmp/netbsdpart -a ! -s /tmp/freespace ]; then
	echo "Didn't find any NetBSD partitions or blocks of free"
	echo "sectors.  You must free up space on your hard disk"
	echo "before installing."
	exit 1
fi
