#!/bin/sh

# Par Dimitri FONTAINE		( fontaine@isty-info.uvsq.fr )

IFS='
'

nom=`basename $0`	# Nom de ce programme (sans le répertoire)
tmp=~/$nom.tmp		# Nom du fichier temporaire
lsopt=-p

if test `uname` != "HP-UX" ; then e="-e" ; fi

if [ "$1" = "-h" -o "$1" = "-help" ]
then
	echo $e "$nom, par Dimitri FONTAINE\t( fontaine@isty-info.uvsq.fr )."
	echo "	$nom [option] [fichier] ... [fichier]"
	echo ""
	echo "	option:"
	echo "		-	lit les arguments sur l'entrée standard"
	echo "		-a	affiche la taille des répertoires même cachés"
	echo "		-c	trouve et affiche la taille des fichiers core"
	echo "		-r	trouve affiche et efface les fichiers core"
	echo ""
	echo "	sans option: indique l'usage du répertoire courant et de ses"
	echo "			sous-répertoires."
	exit
fi

if [ "$1" = "-c" ]
then
	find . -name core -user $USER > $tmp

	if [ -s $tmp ]
	then
		$0 `cat $tmp`
	else
		echo "$nom: fichiers core introuvables"
	fi
	rm -f $tmp
	exit
fi

if [ "$1" = "-r" ]
then
	find . -name core -user $USER > $tmp

	if [ -s $tmp ]
	then
		$0 `cat $tmp`
		rm -f $tmp
	else
		echo "$nom: fichiers core introuvables"
		rm -f $tmp
		exit
	fi
	if find . -name core -user $USER -exec rm {} \;
	then
		echo "$nom: fichiers core détruits"
	else
		echo "$nom: destruction des fichiers core impossible"
	fi
	exit
fi

if [ "$1" = "-a" ]
then
	lsopt=-Ap
	shift
fi

if [ $# -eq 1 -a "$1" = "-" ]
then
	cat > $tmp

	if [ -s $tmp ]
	then
		$0 `cat $tmp`
	fi

	rm -f $tmp
	exit
fi

if [ $# -eq 0 ]
then
	typeset -i dotdone=0
	for i in $(du -s `ls $lsopt|grep /$|sed -e s/.$//` | tr -s '\t' ':' )
	do
		size=`echo $i | cut -d: -f1`
		dir=`echo $i | cut -d: -f2`

		if [ "$dir" = "." ]
		then
			dotdone=1
		fi

		typeset -i s=`echo "$size/2"|bc`
		typeset -i m=`echo "$s/1024"|bc`

		if [ $m -gt 0 ]
		then
			tput bold
			printf "%35s%8d Mo\n" $dir $m
			tput rmso
		else
			printf "%35s%8d Ko\n" $dir $s
		fi
	done
	if [ $dotdone -eq 0 ]
	then
		$0 .
	fi
else
	typeset -i total=0
	typeset -i nb=0

	for i in $(du -s $* | tr -s '\t' ':' )
	do
		size=`echo $i | cut -d: -f1`
		dir=`echo $i | cut -d: -f2`

		typeset -i s=`echo "$size/2"|bc`
		typeset -i m=`echo "$s/1024"|bc`

		total=$s+$total

		if [ $m -gt 0 ]
		then
			tput bold
			printf "%35s%8d Mo\n" $dir $m
			tput rmso
		else
			printf "%35s%8d Ko\n" $dir $s
		fi
		nb=$nb+1
	done

	if [ $nb -gt 1 ]
	then
		typeset -i m=`echo "$total/1024"|bc`

		if [ $m -gt 0 ]
		then
			tput bold
			printf "%35s%8d Mo\n" total $m
			tput rmso
		else
			printf "%35s%8d Ko\n" total $total
		fi
	fi
fi

