#!/bin/bash
#
# For more information type checkVolLabel --help

declare -r cmdbasename=`basename $0`

showhelp(){
cat << EOF

Usage: $cmdbasename [OPTIONS]
Check volumes labels.

OPTIONS:

    --storage=STORAGE         Require. The storage name.
    --pool=POOLNAME           Optional. The Pool name for which volumes will be listed.
                              If omitted all the volumes from all pools will be checked.
    --host=DBHOST             Optional. The host address of the database server (catalog).
                              If omitted 'locahost' will be used.
    --database=DATABASE       Optional. The name of the Catalog's database.
                              If omitted 'bacula' will be used.
    --user=USER               Optional. The name of the user to use to log into
                              Catalog's database. If omitted 'bacula' will be used.
    --password=PASSWORD       Optional. The password of the user to use to log
                              into Catalog's database. If omitted no password will be used.
    --help                    Display this help and exit.

EOF
}

# variables
: ${POOLNAME:=%}
: ${DBHOST:=localhost}
: ${DATABASE:=bacula}

arguments=("$@")
for arg; do
  case "$arg" in
     --help)   showhelp;
               exit 0;;
     --storage=*) STORAGE=${arg#*=};;
     --pool=*) POOLNAME=${arg#*=};;
     --host=*) DBHOST=${arg#*=};;
     --database=*) DATABASE=${arg#*=};;
     --user=*) USER=${arg#*=};;
     --password=*) PASSWORD=${arg#*=};;
     *) printf "%s: unrecognized option \'%s\'" $cmdbasename ${arg%%=*};
        showhelp;
        exit 1;;
  esac
done

if [ -z "$STORAGE" ]; then
  printf "%s: missing --storage=STORAGE option\n" $cmdbasename
  showhelp
  exit 1
fi

VOLUMES=($(mysql --host=$DBHOST --database=$DATABASE --user=$USER --password=$PASSWORD -N -e "SELECT VolumeName from Media, Pool WHERE Media.PoolId=Pool.PoolId AND Pool.Name LIKE \"$POOLNAME\""))

vols=${#VOLUMES[*]}

for ((i=0; i<vols; i++)) do
  bls -L -V ${VOLUMES[i]} $STORAGE > /dev/null
  if [ "$?" = "0" ]; then
    printf "Volume label for %s OK\n" ${VOLUMES[i]}
  else
    printf "Volume label for %s ERROR\n" ${VOLUMES[i]}
  fi
done
