#!/bin/sh
cd $(dirname $0)

set -e
FILE=random.1m
VERBOSE=${VERBOSE:-""}

# Create TEST File
MD5=$(dd if=/dev/urandom bs=10240 count=1024 2>/dev/null |tee ${FILE} |md5sum |awk '{print $1}')
SIZE=$(ls -l ${FILE}|awk '{print $5}')
TSMOPT="-VIRTUALNODENAME=TEST -PASSWORD=TEST -COMPRESSALWAYS=YES"

TSMPIPE=../tsmpipe

echo "MD5 of [${FILE}] is [${MD5}] (${SIZE})"

ln -fs /opt/tivoli/tsm/client/api/bin64/EN_US
export DSMI_DIR=./
export DSMI_CONFIG=dsm.opt

# Send file to TSM
echo "+++ TEST BACKUP ++++!"
echo "+ BACKUP: SEND FILE!"
cat ${FILE} | ${TSMPIPE} -Bcm MD5 -s /test -f ${FILE} ${VERBOSE} -l ${SIZE} -O"${TSMOPT}"

# Send a second time
echo "+ BACKUP: SEND FILE AGAIN!"
cat ${FILE} | ${TSMPIPE} -Bcm MD5 -s /test -f ${FILE} ${VERBOSE} -l ${SIZE} -O"${TSMOPT}"

# List it
echo "+ BACKUP: LIST FILE!"
${TSMPIPE} -Bts /test -f ${FILE} -O"${TSMOPT}"

# Get it back
echo "+ BACKUP: RETRIEVE FILE!"
${TSMPIPE} -Bxs /test -f ${FILE} ${VERBOSE} -O"${TSMOPT}" > ${FILE}.back
RETRIEVE=$(md5sum ${FILE}.back | awk '{print $1}')
if [ "${MD5}" != "${RETRIEVE}" ]; then
	exit 1
else
	echo "+ BACKUP: RETRIEVE VALID (${RETRIEVE})!"
fi

# Purge the last one
echo "+ BACKUP: PURGE!"
${TSMPIPE} -Bgs /test -f ${FILE} ${VERBOSE} -O"${TSMOPT}"

# List it
echo "+ BACKUP: LIST FILE IS PURGED!"
${TSMPIPE} -Bts /test -f ${FILE} -O"${TSMOPT}"

# Delete it
echo "+ BACKUP: DELETE!"
${TSMPIPE} -Bds /test -f ${FILE} ${VERBOSE} -O"${TSMOPT}"

# List it
echo "+ BACKUP: LIST FILE IS DELETED!"
${TSMPIPE} -Bts /test -f ${FILE} -O"${TSMOPT}"
echo "+++ END BACKUP ++++!"

echo "+++ TEST ARCHIVE ++++!"
echo "+ ARCHIVE: SEND FILE!"
cat ${FILE} | ${TSMPIPE} -Acm MD5 -s /test -f ${FILE} ${VERBOSE} -l ${SIZE} -D"Test Archive File" -O"${TSMOPT}"

# Send a second time
echo "+ ARCHIVE: SEND FILE AGAIN! (delay)"
sleep 2
cat ${FILE} | ${TSMPIPE} -Acm MD5 -s /test -f ${FILE} ${VERBOSE} -l ${SIZE} -D"Test Archive File" -O"${TSMOPT}"
DATE=$(date +%m%d%Y:%H%M%S)

# List it
echo "+ ARCIHVE: LIST FILE!"
${TSMPIPE} -Ats /test -f ${FILE} -O"${TSMOPT}"

# Get it back
echo "+ ARCIHVE: RETRIEVE FILE! (${DATE})"
${TSMPIPE} -Axs /test -f ${FILE} -n ${DATE} ${VERBOSE} -O"${TSMOPT}" > ${FILE}.back
RETRIEVE=$(md5sum ${FILE}.back | awk '{print $1}')
if [ "${MD5}" != "${RETRIEVE}" ]; then
	exit 1
else
	echo "+ ARCHIVE: RETRIEVE VALID (${RETRIEVE})!"
fi

# Purge the last one
echo "+ ARCHIVE: DELETE!"
${TSMPIPE} -Ads /test -f ${FILE} -n ${DATE} ${VERBOSE} -O"${TSMOPT}"

# List it
echo "+ ARCHIVE: LIST FILE AFTER DELETE!"
${TSMPIPE} -Ats /test -f ${FILE} -O"${TSMOPT}"
echo "+++ END ARCHIVE ++++!"

rm -f EN_US ${FILE} ${FILE}.back