#!/bin/bash

# ----------------------------------------------------------------------
# donne la taille totale en octets du directory et subdirectory
# (somme de tous les fichiers, sans la taille reservee pour le directory
#  qui est systeme-dependant).
# P. Robert, Janvier 2007
# revu P.R. Novembre 2009, pour portabilite linux-Solaris
# ----------------------------------------------------------------------

appli=`basename $0`

if (test $# = 1 ) 
   then
       if test $1 = help 
           then echo "$appli : Give directory size (octets or Mo)"
                echo "Usage: dir_size"
                echo "       dir_size Mo"
                echo "       dir_size DIR"
                echo "       dir_size DIR Mo"
                exit 1
       fi
fi

Mo=no
dir=.
bb="basename `pwd | sed 's/ /\?/g'`"
nomdir=`$bb`
homdir=$HOME

if test $# != 0
   then
       if (test $# = 1 ) && (test $1  = Mo ) 
          then 
               Mo=yes 
       fi
       
       if (test $# = 1 ) && (test $1 != Mo ) 
          then 
               dir=$1
               nomdir=$1
       fi
       
       if (test $# = 2 ) && (test $2 = Mo )
          then 
               Mo=yes
               dir=$1
               nomdir=$1
       fi
fi

if test -f $homdir/toto$$.tmp ; then rm $homdir/toto$$.tmp ; fi

# on prends tous les champs car certaine lignes peuvent commencer par des blancs

if test -d $dir
   then
      ls -oRq $dir | grep \^- | sed "s/.......... *. //" | cut -d " " -f 2-100 > $homdir/toto$$.tmp
   else
      echo "*** Directory $dir does not exist"
      echo "*** $appli aborted !"
      exit 2
fi

 # max size: 99.999 To

# sous bash, le print en decimal " %13.1d" donne des resultats faux !
# mais ils sont justes en flottants...
#totsize=`awk '{Somme +=$1} END {printf(" %14.1d\n", Somme)}' $homdir/toto$$.tmp`
 totsize=`awk '{Somme +=$1} END {printf(" %14.0f\n", Somme)}' $homdir/toto$$.tmp`
#(s=s+$1 marche aussi)


if  test $Mo = yes 
    then 
         totsize=`expr $totsize / 1000000`
         totsize=`printf " %9.0f" $totsize`
fi

echo "$totsize $nomdir"

rm $homdir/toto$$.tmp 
