#!/bin/sh

SERVERROOT=<msg.RootPath>
DBUTILBIN=${SERVERROOT}/lib
MSGSTOREBIN=${SERVERROOT}/lib

LD_LIBRARY_PATH=${MSGSTOREBIN}:${LD_LIBRARY_PATH}
SHLIB_PATH=${MSGSTOREBIN}:${SHLIB_PATH}
export LD_LIBRARY_PATH SHLIB_PATH

DB_UPGRADE=${DBUTILBIN}/db_upgrade
DB_VERSION=${DBUTILBIN}/db_version
DB_HOME=${SERVERROOT}/data/store/mboxlist

DB_FILES="folder.db quota.db subscr.db peruser.db"

BACKUP_DIR=${DB_HOME}/backup.`date '+%m%d%y%H%M%S'`

UPGRADE_LIST=

# cleanup
cleanup() 
{
  echo "cleaning up tmp files..."
  rm -rf ${BACKUP_DIR}
}

# restore
restore()
{
  cp ${BACKUP_DIR}/* ${DB_HOME}
  cleanup
}

# check version
for f in $DB_FILES
do
  type=`${DB_VERSION} -h ${DB_HOME} $f | awk '{ print $1 }'`
  version=`${DB_VERSION} -h ${DB_HOME} $f | awk '{ print $3 }'`
  if [ $type = 'Btree' -a $version = '6' ]
  then
    UPGRADE_LIST="${UPGRADE_LIST} $f"
  fi 
done

if [ -z "${UPGRADE_LIST}" ]
then
  echo "mboxlist version is up-to-date"
  exit 0
fi

# create backup
mkdir -p ${BACKUP_DIR}

for f in ${UPGRADE_LIST}
do
  echo "backing up ${DB_HOME}/${f}"
  cp ${DB_HOME}/${f} ${BACKUP_DIR}/${f}
  if [ $? -ne 0 ]
  then
    echo "backup failed, existing..."
    cleanup
    exit 1
  fi
done

# upgrade db files
for f in ${UPGRADE_LIST}
do
  if [ -f ${DB_HOME}/${f} ]
  then
  echo "upgrading ${DB_HOME}/${f}"
    ${DB_UPGRADE} -h ${DB_HOME} ${f}
    if [ $? -ne 0 ]
    then
      echo "upgrade failed, restoring backup..."
      restore
      exit 2
    fi
  fi
done

# remove log files
rm -rf log.*

cleanup
exit 0



