#!/bin/sh

BASE_REP="/backuppc/backuppc/pc"

MAX_NBLIGNES_INCR=30
LISTING_FULL=$(printf "%s\n\t%s\t%s\n" "Volumes des dernières sauvegardes complètes :" "Nb fichiers" "Taille" )
LISTING_INCR=$(printf "%s\n\t%s\t%s\n" "Volumes des $MAX_NBLIGNES_INCR dernières sauvegardes incrémentales :" "Nb fichiers" "Taille" )

somme_ligne() {
	TOTAL_FILES=0
	TOTAL_SIZE=0

	# note : c'est un peu sale.
	#        Explications : on fait une boucle basée sur un pipe, les variables dans cette boucle
	#                       deviennent donc locales à cette boucle.
	#                       'faut que je retrouve comment en sortir proprement
	cat - | while read line; do
		echo $(( $TOTAL_FILES + $(printf "%s" "$line" | awk 'BEGIN { FS = "\t" } ; { print $5 }' ) ))
		TOTAL_FILES=$(( $TOTAL_FILES + $( printf "%s" "$line" | awk 'BEGIN { FS = "\t" } ; { print $5 }' ) ))
		TOTAL_SIZE=$(( $TOTAL_SIZE + $( printf "%s" "$line" | awk 'BEGIN { FS = "\t" } ; { print $6 }' ) ))
		printf "%d\t%d\n" "$TOTAL_FILES" "$TOTAL_SIZE"
	done | tail -n 1
}

cd "$BASE_REP"

for REP in *; do
	# On ne prend que les dossiers qui contiennent un fichier non-vide "backups"
	if [ ! -d "$REP" ]; then
		continue
	fi
	if [ ! -s "$REP/backups" ]; then
		continue
	fi

	# Listing full
	LISTING_FULL="$( printf "%s\n%s\t%s" "$LISTING_FULL" "$REP" "$( cat "$REP/backups" | egrep "^[0-9]+[[:space:]]+full" | tail -n 1 | somme_ligne )" )"

	# Listing incrémental
	#décompte nb sauv.
	NBLIGNES_INCR="$( cat "$REP/backups" | egrep "^[0-9]+[[:space:]]+incr" | wc -l )"
	if [ "$NBLIGNES_INCR" -gt $MAX_NBLIGNES_INCR ]; then
		NBLIGNES_INCR=$MAX_NBLIGNES_INCR
	fi
	LISTING_INCR="$( printf "%s\n%s (%dj)\t%s" "$LISTING_INCR" "$REP" "$NBLIGNES_INCR" "$( cat "$REP/backups" | egrep "^[0-9]+[[:space:]]+incr" | tail -n $MAX_NBLIGNES_INCR | somme_ligne )" )"


done

echo "$LISTING_FULL"
echo
echo "$LISTING_INCR"