#! /bin/sh

CP="/bin/mv"
BACKUP=

CFDIR=/etc/mail/jchkmail
WDIR=/var/jchkmail
ROOTDIR=/var/jchkmail
CDBDIR=$ROOTDIR/cdb
WDBDIR=$ROOTDIR/wdb
LOGDIR=$ROOTDIR/files


usage()
{
  echo "Usage: $0 [options]"
  cat <<EOF
    Options :
      -h           Help (this message)
      -c           Use "cp" instead of "mv"
      -b           backup original directories before migration

  You can use this script if you're upgrading j-chkmail from a version
  older than 1.11.0 RC3.

  Suggested way to launch this script is with "-b" option : if something
  goes wrong, you can restore initial data from tar files created inside
  /tmp directory

  You shall launch this script just after you compile j-chkmail and just
  before you install the new version.

EOF
}

set -- `getopt hcb $*`
if [ $? != 0 ]
then
  usage
  exit 2
fi

for i in $*
do
  case $i in
    -h)
       usage
       exit 0
       ;;
    -c)
       CP="/bin/cp -p"
       shift
       ;;
    -b)
       BACKUP=1
       shift 1
       ;;
    --)
       shift
       break
       ;;
  esac
done

#
# backup old data
#
if [ "$BACKUP" = "1" ];
then
  cd /etc/mail
  tar cf /tmp/etc-jchkmail.tar jchkmail
  gzip -f /tmp/etc-jchkmail.tar
  cd /var
  tar cf /tmp/var-jchkmail.tar jchkmail
  gzip -f /tmp/var-jchkmail.tar
fi

#
# create new directories
#
for dir in $CDBDIR $WDBDIR $LOGDIR
do
  mkdir -p $dir
  chown smmsp:smmsp $dir
done

#
# populate cdb directory
#
cd $CFDIR
CDBF="j-policy*db  j-rcpt*db  j-urlbl*db  j-bayes*db"
$CP $CDBF  $CDBDIR
CDBF="j-policy*txt j-rcpt*txt j-urlbl*txt j-bayes*txt"
$CP $CDBF  $CDBDIR
CDBF="Makefile* get-urlbl*"
$CP $CDBF  $CDBDIR


#
# populate wdb directory
#
cd $WDIR
WDBF="j-grey*db j-res-cache*db"
$CP $WDBF  $WDBDIR

#
# populate files directory
#
cd $WDIR
FILES="j-*data"
$CP $FILES $LOGDIR
LOGF="j-history j-files j-virus j-xreport j-regex j-stats j-state j-series.txt"
$CP $LOGF  $LOGDIR


FIN=etc/j-chkmail.cf.running
[ -f $FIN ] && sed s#/var/jchkmail/j#j# $FIN > /tmp/j-chkmail.cf.1
FIN=/etc/mail/j-chkmail.cf.running
[ -f $FIN ] && sed s#/var/jchkmail/j#j# $FIN > /tmp/j-chkmail.cf.2


