#!/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`

# on eclate les variables pouvant contenir un blanc
if test $# -gt 0
   then set $*
fi

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

Mo=no
nomdir=.
homdir=$HOME

if test $# != 0
   then
       if (test $# = 1 ) && (test $1  = Mo ) 
          then 
               Mo=yes 
       fi
       
       if (test $# = 1 ) && (test $1 != Mo ) 
          then 
               nomdir=$1
       fi
       
       if (test $# = 2 ) && (test $2 = Mo )
          then 
               Mo=yes
               nomdir=$1
       fi
       
       if (test $# -ge 2 )
           then
#          echo "$appli: trop d'arguments ou blanc dans le nom du directory"
           echo $* > $homdir/toto2$$.tmp
           nomdir=`cat $homdir/toto2$$.tmp | sed "s/ /\?/g"`
           
           cat $homdir/toto2$$.tmp | grep "Mo$" > /dev/null 2>&1
           if test $? = 0
              then 
                 nomdir=`echo $nomdir | sed 's/.Mo$//'`
                 Mo=yes
              else
                 Mo=no
           fi
           rm $homdir/toto2$$.tmp
#          echo "$appli: $nomdir" 
       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 $nomdir
   then
      ls -oRq $nomdir | grep \^- | sed "s/.......... *. //" | cut -d " " -f 2-100 > $homdir/toto$$.tmp
   else
      echo "*** Directory $nomdir 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 
