#!/bin/bash 

ucamdsm="/usr/local/bin/ucamdsm"

echo "Invoked with: $0 $@"
echo "My PID is $$"

###################################################################
# Purpose: usage information 
###################################################################
function usage()
{
cat << EOF
usage: $0 options

This script saves the list of recycled volumes in files

OPTIONS:
   -h                                  Show this message
   -o /path/to/dir/                    Path of where the recycled volumes information will be saved
   -c /path/to/secrets.json            Secret file containing URL and credential to access Dell SC

E.g.
   $0 -o /path/to/dir/ -c /path/to/secrets.json

NB. 
1. /path/to/secrets.json must be in the following format:
{
    "dsm_host": "example.com",
    "dsm_user": "user",
    "dsm_password": "password"
}

2. ucamdsm must be installed and located under /usr/local/bin/
EOF
}

###################################################################
# Parse the args 
###################################################################

while getopts "ho:c:" opt
do
  case $opt in
    h)
      usage
      exit
      ;;
    o)
      output_dir=$OPTARG
      ;;
    c)
      secrets=$OPTARG
     ;;
    ?)
      usage
      exit
      ;;
  esac
done

# check required arguments
if [ -z "$output_dir" ] || [ -z "$secrets" ]
then
   usage
   exit
fi

mkdir -p "$output_dir"
datestamp=$(date '+%Y%m%d')
output_file="${output_dir}/${datestamp}"

recycledVols=$($ucamdsm --file $secrets list --object recycledVols)

if [[ $recycledVols == *"[Command succeeded - Returns True]"* ]]
then
    echo "$recycledVols" | grep "WCDC Storage Center" > "${output_file}.wcdc"
    echo "$recycledVols" | grep "SB Storage Center" >"${output_file}.sby"
    echo "$recycledVols" | grep "WCDC D14 (overflow) Storage Center" >"${output_file}.wcdc_overflow"
    echo "Command succeeded."
    exit 0
else
    echo "Command failed. Please check the ucamdsm log file in /var/log/ucamdsm/."
    exit 1
fi
