#
# Disk Hogs Summary - disk usage by directory beneath this, sorted
# by size.
#
# Directories that contain less than 100k are silently removed.
dhs() {
	du -kd 1000 "$@" | awk '($1 >= 100)' | sort -rn
}

#
# APM data watcher.  Useful for seeing how the battery REALLY behaves, as
# opposed to the silly output from apm(8)
#
apmlog() {
	local delay
	delay=$1
	if [ "$delay" -eq "0" ]; then
		delay=60
	fi
	while true; do
		echo -n $(date "+%Y-%m-%d %H:%M:%S") ''
		apm | apmwatch
		sleep $1
	done
}

#
# I use a CVS repository per project, stored in my home directory.
# The following function (for User CVS) lets me use the repositories easily.
#
ucvs() {
	local repo
	repo=$HOME/Repos/$1
	shift
	if [ ! -d $repo -o ! -d $repo/CVSROOT ]; then
		# Allow "init" even if an uninitialized repository
		if [ "$1" = "init" ]; then
			cvs -d $repo "$@"
			return $?
		fi
		echo "Missing/damaged repository $repo" 1>&2
		return 1
	fi
	cvs -d $repo "$@"
}

#
# CD to where the source of a command is
#
cdsrc() {
	local dir
	local dir1

	if ! [ -f =$1 ]; then
		echo "Unable to find command $1" 1>&2
		return 1
	fi
	dir=$(echo =$1 | sed -e 's|^/||' -e 's|usr/|usr.|')
	if [ -d "/usr/src/$dir" ]; then
		cd "/usr/src/$dir"
	elif [ -d "/usr/src/gnu/$dir" ]; then
		cd "/usr/src/gnu/$dir"
	else
		dir=$(echo $dir | sed 's|/|/*/|')
		dir1=$(sh -c "ls -d /usr/src/$dir" 2> /dev/null)
		if echo $dir1 | grep -q ' '; then
			echo "Several alternatives - cannot determine." 1>&2
			echo $dir1 | sed -e 's| |\n|g' 1>&2
			return 1
		fi
		if [ -d $dir1 ]; then
			cd $dir1
			return 0
		fi
		dir1=$(sh -c "ls -d /usr/src/gnu/$dir" 2> /dev/null)
		if echo $dir1 | grep -q ' '; then
			echo "Several alternatives - cannot determine." 1>&2
			echo $dir1 | sed -e 's| |\n|g' 1>&2
			return 1
		fi
		if [ -d $dir1 ]; then
			cd $dir1
			return 0
		else
			echo "Unable to find directory for $1" 1>&2
			return 1
		fi
	fi
}

#
# Find some file in the source code
#
lsrc() {
	locate $1 | grep '^/usr/src'
}

#
# Set width/height of xterm.  Use "" or missing parameter to keep present
# size.
#
xt() {
	echo -n "\e[8;$2;$1t"
}

#
# Change directory to the one in the CVS repo we are working from (if
# possible)
#
cdrepo() {
	if [ ! -f CVS/Root -o ! -f CVS/Repository ]; then
		echo "Missing CVS/Root or CVS/Repository" 1>&2
		return 1
	fi
	if grep : CVS/Root > /dev/null; then
		echo "$(cat CVS/Root) is a remote repository" 1>&2
		return 1
	fi
	repodir=$(cat CVS/Root)/$(cat CVS/Repository)
	if [ -d $repodir ]; then
		cd $repodir
	else
		echo "$repodir does not exist" 1>&2
		return 1
	fi
}

#
# Set the xterm background color
#
xtbg() {
	if (echo $1 | egrep '^([0-9a-f]{6}|[0-9A-F]{6})$' > /dev/null); then
		echo "\e]11;#$1\007"
	else
		echo "\e]11;$1\007"
	fi
}

