#!/bin/bash

# This script takes two arguments $HOST and $NUMB, and give you a text file
# whit all the files that have been backed up whit Bacula from the $HOST for
# the last $NUMB of incremental backups.

# Writen by Geir Asle Borgen whit help form users of ##oflug on FreeNode and
# bacula-users@lists.sourceforge.net
# Date: 2006.02.28

# Constans
# 1st argument is the backedup host
HOST=$1
# 2nd argument is the number of jobs (last jobs)
NUMB=$2
DIR=/tmp/bacula

mkdir -p $DIR

# Getting the jobid's to the $NUMB last jobs on $HOST
JOBID=`(bconsole <<END_OF_DATA
list jobs
quit
END_OF_DATA
) | grep $HOST | grep -v "| F" | tail -$NUMB | cut -c2-7`

# Listing all files backed up on all the $JOBID's, stored in separat files.
# Stripping all other info. Just full path and filenames.
for i in `echo $JOBID`
do
(bconsole <<END_OF_DATA
list files jobid=$i
quit
END_OF_DATA
) | grep \/ |cut -d\| -f2 | tr -s ' \t' '  ' | grep -v "\/ *$" |cut -c2- > $DIR/$i
done

# Reading all $JOBID-files and commparing them line by line for exactly 
# matching lines. The resolt is stored in text files.
if [ $NUMB -ge 1 ]
then
   COUNT=0
   while test "$COUNT" != "$NUMB"
   do
      for JOBIDCOUNT in `echo $JOBID`
      do
         COUNT=`expr $COUNT + 1`

         if [ "$COUNT" == "1" ]
         then
            TMP=$JOBIDCOUNT
         elif [ "$COUNT" == "2" ]
         then
            for FILESTRING in `cat $DIR/$TMP`
            do
               grep -x "$FILESTRING " $DIR/$JOBIDCOUNT >> $DIR/bacula$COUNT
            done
            y=$COUNT
         else
            for FILESTRING in `cat $DIR/bacula$y`
            do
               grep -x "$FILESTRING " $DIR/$JOBIDCOUNT >> $DIR/bacula$COUNT
            done
            y=$COUNT
         fi
      done
   done
fi

# Cleaning up, finale resolt storetd in $DIR/resolt.txt
for i in `echo $JOBID`
do
   rm $DIR/$i
done
mv $DIR/bacula$NUMB $DIR/resolt.txt
rm $DIR/bacula*
