#! /bin/sh
# set -xv
#=========================================================================
# Copyright (C) VMware, Inc. 1986-2011.  All Rights Reserved..
#
# Name - postconv.sh
# Installed as - postconv
#
# Purpose - Common script for fixing up large objects detected during
#           low level conversion. This script is used for all
#           conversion kinds, i.e.: 6.1 -> 2.x, 1.x -> 2.x, 2G -> 2.x
#           6.2.x -> 2.x
#
# Convert large objects found during conversion.
#
# $Id: postconv.sh,v 1.12 2008-01-09 22:50:52 stever Exp $
#
#=========================================================================


if [ "a$GEMSTONE" = "a" ]; then
  echo "ERROR: GemStone scripts require a GEMSTONE environment variable."
  echo "       Please set it to the directory where GemStone resides."
  exit 1
fi

# maintenance symbols
comid="postconv"              # this script's name

# make sure of a minimum path
PATH=:/bin:/usr/bin:/usr/ucb:$PATH; export PATH

. $GEMSTONE/bin/misc.sh

defaultErrorControl

info() {
  echo $comid[INFO]: $*
}
error() {
  echo $comid[ERROR]: $*
}
usage() {
  cat <<EOF
Usage:
postconv [-c <numCacheWamerGems>][h][-s <stoneName>][-n <numberOfSessions>]
         [-t <tempObjCacheSize]
Environment Requirements:
    GEMSTONE          set to a 2.x GemStone/S 64 Bit product tree
    upgradeLogDir     set to a writable directory used in previous steps
Parameters:
    -c <numCacheWamerGems> 
        Run <numCacheWamerGems> cache warmer gems before starting post-conversion.
        Default: 0 (no cache warming)
    -h print this Usage and exit
    -s <stoneName>
        where <stoneName> is the name of a running 2.x stone that has already
        been through the previous conversion steps.  Default: gs64stone
    -n <numberOfSessions>
        where <numberOfSessions> is the number of parallel sessions to run.
        Default: 1
    -t <tmpObjCacheSize>
        size of GEM_TEMPOBJ_CACHE_SIZE in KB.
        Default: same value as that used in the upgradeImage step. The Default
        for that step is 200000.
EOF
}

# defaults
stoneName=gs64stone
numberOfSessions=1
numCacheWarmers=0

while getopts "hc:n:s:t:" opt; do
  case $opt in
    h) usage; exit 0 ;;
    c) numCacheWarmers=$OPTARG ;;
    n) numberOfSessions=$OPTARG ;;
    s) stoneName=$OPTARG ;;
    t) tmpObjCacheSize=$OPTARG ;;
   \?) error "bad arg: $opt"; usage; exit 1 ;;
  esac
done
export stoneName

if [ "x$tmpObjCacheSize" != "x" ]; then
  # We've been handed a value for GEM_TEMPOBJ_CACHE_SIZE, so we will
  # append $upgradeLogDir/conversion.conf (written by upgradeImage* step).
  # First, range check the value given
  if [ $tmpObjCacheSize -gt 1000000 ] || [ $tmpObjCacheSize -lt 1000 ]; then
    echo "ERROR: Cannot set GEM_TEMPOBJ_CACHE_SIZE to $tmpObjSize."
    echo "ERROR: This value must be between 1000 and 1000000."
    usage
    exit 1
  fi
  # Write the conf file
  cat <<EOF >> $upgradeLogDir/conversion.conf
GEM_TEMPOBJ_CACHE_SIZE = $tmpObjCacheSize;
GEM_TEMPOBJ_INITIAL_SIZE = $tmpObjCacheSize;
EOF
  
fi

# make sure $upgradeLogDir has been set
info "verifying upgradeLogDir..."
if [ a$upgradeLogDir = "a" ]; then
  error "The environment variable upgradeLogDir has not been set."
  usage
  exit 1
elif [ ! -d $upgradeLogDir ]; then
  error "$upgradeLogDir is not a directory."
  usage
  exit 1
fi
info "...found upgradeLogDir..."

# make sure $upgradeLogDir is writable
touch $upgradeLogDir/tmp$$ 2>/dev/null 
if [ "$?" != "0" ]; then
  error "$upgradeLogDir is not writable."
  usage
  exit 1
fi
rm $upgradeLogDir/tmp$$
info "...upgradeLogDir is writable."

# we need to know if it's a GS61 conversion or not.
# make sure we do.
if [ -r $upgradeLogDir/from61_3.out ]; then
  is2G=0
  is61=1
  is62=0
  arg61=true
  info "...source repository is a GemStone 6.1 repository."
elif [ -r $upgradeLogDir/from62_3.out ]; then
# effectively same as 6.1 upgrade
  is2G=0
  is61=0
  is62=1
  arg61=true
  info "...source repository is a GemStone 6.2.x repository."
elif [ -r $upgradeLogDir/from1x_3.out ]; then
  is2G=0
  is61=0
  is62=0
  arg61=false
  info "...source repository is a GemStone64 1.x repository."
elif [ -r $upgradeLogDir/from2g_3.out ]; then
# same oop format as 1.x
  is2G=1
  is61=0
  is62=0
  arg61=false
  info "...source repository is a GemStone2G 1.x repository."
elif [ -r $upgradeLogDir/from61_4.out ]; then
  error "Conversion from 6.1 already completed"
  exit 1
elif [ -r $upgradeLogDir/from62_4.out ]; then
  error "Conversion from 6.2 already completed"
  exit 1
elif [ -r $upgradeLogDir/from2g_4.out ]; then
  error "Conversion from 2G 1.x already completed"
  exit 1
elif [ -r $upgradeLogDir/from1x_4.out ]; then
  error "Conversion from 1.x already completed"
  exit 1
else
  error "previous upgrade step(s) did not complete successfully."
  exit 1
fi

# Make sure the AllLrgObjs.bm is readable
largeObjsFile=$upgradeLogDir/AllLrgObjs.bm

if [ ! -r $largeObjsFile ]; then
  error "Bitmap file $largeObjsFile is not readable or does not exist."
  exit 1
fi

# make sure stone is running
info "verifying $stoneName is running..."
$GEMSTONE/bin/waitstone $stoneName -1 > /dev/null 2>&1
status=$?
if [ $status -ne 0 ]; then
  error "...no stone named $stoneName found"
  usage
  exit $status
fi
info "...$stoneName is running."


#-------------------------------------------------
# take the LrgObjs.topaz_* files and create files for the large object
# conversion

# clean up from any previous runs
rm $upgradeLogDir/allLrgObjs.topaz $upgradeLogDir/convertLgObjs* \
   $upgradeLogDir/topaz-*.log postconv*.* cachewarmgem*.* >/dev/null 2>&1

# put the cache warmer logs in $upgradeLogDir
here=`pwd`
cd $upgradeLogDir

# start cache warmer gems if specified
if [ $numCacheWarmers -gt 0 ]; then
  info "starting cache warmers..."
  if [ $numCacheWarmers -gt 16 ]; then
    numCacheWarmers=16
  fi
  $GEMSTONE/bin/startcachewarmer -n$numCacheWarmers -s$stoneName -W
  status=$?
  if [ $status -eq 0 ]; then
    info "...successfully started cache warmers."
  else
    error "...cache warming failed!"
    exit $status
  fi
fi

info "...cache warming completed"
# back where we started
cd $here

count=1
fileNum=0

# file numbers are 0-based.  the first input and output file is 0
# gem nums are 1-based.  the first gem is gem 1
#
while [ $count -le $numberOfSessions ]; do
  convFile=$upgradeLogDir/postconv$fileNum.topaz
  thisLogFile=$upgradeLogDir/postconv-$fileNum.log
  echo set user SystemUser pass swordfish gemstone $stoneName > $convFile
  echo "display resultcheck" >> $convFile
  echo "omit oops" >> $convFile
  echo "omit bytes" >> $convFile
  echo "limit oops 50" >> $convFile
  echo "limit bytes 100" >> $convFile
  echo "iferror stack" >> $convFile
  echo login >> $convFile
  echo time >> $convFile
  echo run >> $convFile
  echo Object runPostConversionForGem: $count of: $numberOfSessions is61: $arg61 bmFile: \'$largeObjsFile\' >> $convFile
  echo % >> $convFile
  echo time >> $convFile
  echo logout >> $convFile
  echo errorcount >> $convFile
  $GEMSTONE/bin/topaz -i -l -e $upgradeLogDir/conversion.conf < $convFile \
                                                           > $thisLogFile 2>&1 &
  thisPid=$!
  logFiles="$thisLogFile $logFiles"
  pids="$thisPid $pids"
  info "spawned topaz with input file $convFile, PID = $thisPid"
  count=`expr $count + 1`
  fileNum=`expr $fileNum + 1`
done

#-------------------------------------------------
# wait for the topaz sessions to exit
info "waiting for topaz processes with the following PIDs:"
info "$pids"
wait $pids

#-------------------------------------------------
# grep topaz log files for error count != 0
errorFound=0
for log in $logFiles; do
# tail on HPUX needs this next line
  echo >> $log 
  tail -2 $log | head -1 | egrep -e 'topaz> 0' >/dev/null
  status=$?
  if [ $status -ne 0 ]; then
    error "found non-zero error status in $log"
    errorFound=1
  fi
done

if [ $errorFound -eq 0 ]; then
  if [ $is61 -eq 1 ]; then
    rm $upgradeLogDir/from61_3.out >/dev/null 2>&1
    touch $upgradeLogDir/from61_4.out
    info "Success! Conversion process from GemStone 6.1 to GemStone64 2.x completed."
  elif [ $is62 -eq 1 ]; then
    rm $upgradeLogDir/from62_3.out >/dev/null 2>&1
    touch $upgradeLogDir/from62_4.out
    info "Success! Conversion process from GemStone 6.2.x to GemStone64 2.x completed."
  elif [ $is2G -eq 1 ]; then
    rm $upgradeLogDir/from2g_3.out >/dev/null 2>&1
    touch $upgradeLogDir/from2g_4.out
    info "Success! Conversion process from GemStone 2G 1.x to GemStone64 2.x completed."
  else
    rm $upgradeLogDir/from1x_3.out >/dev/null 2>&1
    touch $upgradeLogDir/from1x_4.out
    info "Success! Conversion process from GemStone64 1.x to GemStone64 2.x completed."
  fi
  exit 0
else
  error "conversion process produced errors."
  error "Check log files listed above."
  exit 1
fi
