#!/usr/bin/ksh

##### {COPYRIGHT-TOP} ##############################################
# IBM Confidential
# OCO Source Materials
# 5724-V51
#
# (c) Copyright IBM Corp. 2000, 2008 All Rights Reserved.
#
# The source code for this program is not published or otherwise
# divested of its trade secrets, irrespective of what has been
# deposited with the U.S. Copyright Office.
##### {COPYRIGHT-END} ##############################################

STARTTIME=`date`
echo $0 "Last update: 20090320 Version 5.3.2 FP13"
# Usage of the file
if [[ $# -ne 4 ]]
then
 echo "Usage "
 echo $0 "--db=databasename --dbuser=touser --dbpassword=touserpassword --backupdir=DumpDirectory"
 echo "Example " $0 " --db=mdmpimdb --dbuser=mdmpim2 --dbpassword=ibm4pim2 --backupdir=/u01/backup/jul10"
 exit 0
fi

# Declare the variables
DBName=`echo $1 |cut -d "=" -f2`;export DBName
typeset -u DBUSER=`echo $2 |cut -d "=" -f2`;export DBUSER
DBUserPassword=`echo $3 |cut -d "=" -f2`;export DBUserPassword
DUMPDIR=`echo $4 |cut -d "=" -f2`;export DUMPDIR
NOCREATESCHEMA=`echo $5|cut -d "=" -f2`; export NOCREATESCHEMA
cd ${DUMPDIR}

# ************************** FILE CHECKS ***************************************
if [[ -a tab9.ixf.gz ]]
then 
  gunzip *.gz
fi
if [[ ! -s db2look.sql ]] || [[ ! -s db2move.lst ]]
then
  echo "FILE NOT EXISTS"
  exit 0
fi

# Read the EXPORT.out file for any errors
if [ `grep -c SQLSTATE ${DUMPDIR}/EXPORT.out` -ne "0" ]
 then
  echo "Error encountered while exporting, Pls. verify and execute again"
  echo "The file is ${DUMPDIR}/EXPORT.out "
  exit 0;
fi
rundate=`date +%m-%d-%H:%M:%S`
cat *.msg > all_msgs_${rundate}.out

# ********************** DROP SCHEMA *******************************************
db2 "connect to ${DBName} user ${DBUSER} using ${DBUserPassword}"
echo "DROP TABLES"

db2 -x "select 'drop table '|| rtrim(tabschema) ||'.'||tabname||';' from syscat.tables where type = 'T' and tabschema ='"${DBUSER}"'" > ${DUMPDIR}/drptbls.cmd
db2 -x "select 'drop alias '|| rtrim(tabschema) ||'.'||tabname||';' from syscat.tables where type = 'A' and tabschema ='"${DBUSER}"'" > ${DUMPDIR}/drpali.cmd

db2 -x "select 'drop sequence " $DBUSER ".', seqname, ';'  from syscat.sequences where seqschema=upper('"${DBUSER}"')" > ${DUMPDIR}/drpseq.cmd
db2 -x "select 'drop view '|| rtrim(tabschema) ||'.'||tabname||';' from syscat.tables where type = 'V' and tabschema ='"${DBUSER}"'" > ${DUMPDIR}/drpvw.cmd

db2 -tvf ${DUMPDIR}/drpseq.cmd > drop_${DBUSER}.log
db2 -tvf ${DUMPDIR}/drptbls.cmd >> drop_${DBUSER}.log
db2 -tvf ${DUMPDIR}/drpali.cmd >> drop_${DBUSER}.log
db2 -tvf ${DUMPDIR}/drpvw.cmd >> drop_${DBUSER}.log

for e in 1 2; do
  functionlist=`db2 -x "select rtrim(funcschema)||'.'||specificname from syscat.functions where funcschema = upper('${DBUSER}')"`
  proclist=`db2 -x "select rtrim(procschema)||'.'||procname from syscat.procedures where procschema = upper('${DBUSER}')"`
  for i in $functionlist; do
    db2 -v "drop specific function ${i}" >> drop_${DBUSER}.log
  done
  for j in $proclist; do
    db2 -v "drop procedure ${j}" >> drop_${DBUSER}.log
  done
done

# ******************************************************************************
# Filter for the import only tables from db2look file
# to create only tables, indexes and functions. NO sequences will be created
#sed -e '/CONNECT TO/,/CREATE SCHEMA/d' -e '/-- Database and Database Manager configuration parameters/,/-- Environment Variables settings/d' -e "s/_TEMP_/\!/" -e "s/_DU2_/\!/g" -e "s/_DUP_/\!/g" -e "s/_MIC_/\!/g" db2look.sql  > create_schema.sql
awk '/CREATE/||/ALTER/||/SET/,/\;/' db2look.sql > create_schema.sql

cp  db2move.lst  db2move_${rundate}bkp.lst
grep -E -v "_TEMP_|_DU2_|_DUP_|_MIC_" db2move.lst > db2move_mod.lst
mv db2move_mod.lst db2move.lst

exporteduser=`grep "SET CURRENT SCHEMA = " create_schema.sql | sort -u |cut -d "=" -f2 |cut -d "\"" -f2|cut -d " " -f1`;export exporteduser
#echo $exporteduser

if [ "${exporteduser}"  !=  "$DBUSER" ]
then
 # replace the username
 sed -e "s/${exporteduser}/$DBUSER/g"  create_schema.sql > create_schema_${DBUSER}.sql
 sed -e "s/${exporteduser}/$DBUSER/g"  db2move.lst >  db2move.lst_${DBUSER}.sql
 mv db2move.lst_${DBUSER}.sql db2move.lst

else
 cp create_schema.sql create_schema_${DBUSER}.sql
fi

echo "commit work;" >> create_schema_${DBUSER}.sql
echo "terminate;" >> create_schema_${DBUSER}.sql

# create only tables, indexes and functions
db2 "connect to ${DBName} user ${DBUSER} using ${DBUserPassword}"
echo "CREATE TABLES"
# try to create table seqtab, in case it was not included in db2look output
# generated by previous versions of db2_export.sh
db2 -v "create table seqtab (seqname varchar(30), latestval integer)" >  create_schema_${DBUSER}.log

db2 -tvf create_schema_${DBUSER}.sql >  create_schema_${DBUSER}.log
# Added due to a bug in db2look
db2 "create index DOA_0_UK on tdoc_doa_doc_attributes(doa_doc_id, doa_cmp_id, doa_name) ALLOW REVERSE SCANS " >> create_schema_${DBUSER}.log
db2 "create index CTG_1_UK on tctg_ctg_catalog(ctg_company_id, ctg_name) ALLOW REVERSE SCANS " >> create_schema_${DBUSER}.log

# ******************************************************************************
# Running runstats to collect statistics on the tables and indexes for optimizer
db2 "connect to ${DBName} user ${DBUSER} using ${DBUserPassword}"
echo "RUNSTATS"
db2 -x "select 'runstats on table ${DBUSER}.'||tabname||' and indexes all set profile only;' from syscat.tables where TABSCHEMA = '${DBUSER}' and type = 'T'" >runstats.sql
#cat runstats.sql|grep -i "runstats on table" > runstats_${DBUSER}.sql
db2 -tvf runstats.sql > runstats_${DBUSER}.log
db2 terminate

# Import
# ******************************************************************************
db2 "connect to ${DBName} user ${DBUSER} using ${DBUserPassword}"
echo "LOADING" 
grep " 0 rows" EXPORT.out > empty_tables.out
echo "LOADING DATA" `date` > load_${DBUSER}.log 
lines=`awk 'BEGIN {ORS=""} {for (i=1; i<=NF; i++) print $i; print "\n"}' ${DUMPDIR}/db2move.lst`
for line in $lines; do
  TABLENAME=`echo $line |cut -d "!" -f2 | cut -d "." -f2| cut -d "\"" -f2`
#  echo "Loading data for table $TABLENAME"
  IXFFILE=`echo $line | cut -d "!" -f3`
  MSGFILE=`echo $line | cut -d "!" -f4`
  COUNT=`grep -c ${TABLENAME} empty_tables.out`  
  # only kick off load command, if table has rows to load
  if [ "$COUNT" -eq "0" ] ; then  
    echo "load from ${IXFFILE} of IXF modified by pagefreespace=0 savecount 100000 messages ${MSGFILE} replace into ${TABLENAME} statistics use profile nonrecoverable indexing mode rebuild" >> load_${DBUSER}.log
    db2 "load from ${IXFFILE} of IXF modified by pagefreespace=0 savecount 100000 messages ${MSGFILE} replace into ${TABLENAME} statistics use profile nonrecoverable indexing mode rebuild" >> load_${DBUSER}.log
  fi
done

# ******************************************************************************
db2 -x "connect to ${DBName} user ${DBUSER} using ${DBUserPassword}"
echo "REMOVE CHECK-PENDING STATUS"
echo "Check pending status" `date` > check_pending_${DBUSER}.log
for e in 1 2 3; do
#  echo "iteration $e"
#  echo " Get list of tables in check pending status"
  integritylist=`db2 -x "select name from sysibm.systables where status ='C' and creator='${DBUSER}'"`
  for i in $integritylist; do
    db2 -x "set integrity for ${i} immediate checked" >> check_pending_${DBUSER}.log
  done
done
db2 terminate

# Importing the Sequences from the backup
# ******************************************************************************
db2 -x "connect to ${DBName} user ${DBUSER} using ${DBUserPassword}"
echo "CREATE SEQUENCES"
db2 -x "select 'create sequence ${DBUSER}.',seqname,' start with ',latestval,' cache 20;' from seqtab" > create_sequences_${DBUSER}.sql
#cat create_sequences.sql | grep -i "create sequence ${DBUSER}" > create_sequences_${DBUSER}.sql
db2 -tvf create_sequences_${DBUSER}.sql > create_sequences_${DBUSER}.log

# If the sequences already exist - update the values
sed -e "s/create sequence/alter sequence/g" create_sequences_${DBUSER}.sql > alter_sequences.sql
sed -e "s/start with/restart with/g" alter_sequences.sql > alter_sequences_${DBUSER}.sql
db2 -tvf alter_sequences_${DBUSER}.sql > alter_sequences_${DBUSER}.log
db2 terminate

# Restoring the original files for the next import
rm create_schema.sql
rm create_schema_${DBUSER}.sql
rm create_sequences_${DBUSER}.sql
rm runstats.sql
ENDTIME=`date`
echo "start time $STARTTIME"
echo "end time $ENDTIME"
echo "CHECK .log FILES FOR SUCCESS"
exit 0

