#!/bin/bash
#set -x
# Usage of the file
if [[ $# -ne 6 ]]
then
 ${ECHO} CREATE_COMPANY_INFO_USAGE_SH
 ${ECHO} "db2_export.sh --db=databasename --dbuser=exportuser --dbpassword=exportuserpassword --backupdir=Directory --bkpfile=bkpfilename"
 ${ECHO} MIGRATION_INFO_EXAMPLE_SH " db2_export.sh --db=wpcdb --dbuser=wpc1 --dbpassword=ibm4wpc --backupdir=/u01/backup --bkpfile=july10bkp"
 exit 0
fi

# Declare the variables
DBName=`${ECHO} $1 |${CUT} -d "=" -f2`;export DBName
DBUserName=`${ECHO} $2 |${CUT} -d "=" -f2`;export DBUserName
DBUserPassword=`${ECHO} $3 |${CUT} -d "=" -f2`;export DBUserPassword
DBBackup_Dir=`${ECHO} $4 |${CUT} -d "=" -f2`;export DBBackup_Dir
BKPfile=`${ECHO} $5 |${CUT} -d "=" -f2`;export BKPfile
# Make directory for the dumpfile with the backup file suffix
${RM} ${DBBackup_Dir}/${BKPfile}
${MKDIR} ${DBBackup_Dir}/${BKPfile}
cd  ${DBBackup_Dir}/${BKPfile} 

# set the database character set
db2set DB2CODEPAGE=1208

# Export the syntax of table creation and index
db2look -d ${DBName} -o db2look.sql  -e -p -r  -f -z  ${DBUserName} -i ${DBUserName} -w ${DBUserPassword}

# connect to database to collect the lastest sequence values
db2 -v "connect to ${DBName}  user ${DBUserName}  using ${DBUserPassword}"

# ignore SQL0204N warning

db2 -v "drop table seqtab"
db2 -v "create table seqtab (seqname varchar(30), latestval integer)"
db2 -v "select 'insert into seqtab values ('||seqname||',nextval for '||seqname||');' from syscat.sequences where lower(SEQSCHEMA)='${DBUserName}'" >seq.sql
${CAT} seq.sql | ${GREP} "insert into seqtab values (" > seqins.sql
${CAT} seqins.sql | ${GREP} -v "select" > seqinsert.sql
${ECHO} "commit;" >> seqinsert.sql
${SED} -e "s/(/('/g" seqinsert.sql > seqinsert1.sql
${SED} -e "s/,nextval/',nextval/g" seqinsert1.sql > seqinsert2.sql
db2 -tvf seqinsert2.sql | tee insert_seq_values.log

${RM} seq.sql seqinsert.sql seqinsert1.sql seqinsert2.sql

# Export the Data
db2move ${DBName} export -u ${DBUserName} -p ${DBUserPassword} -sn ${DBUserName}

# Create a tar of the total files in the Backup Dir
tar cfp  ${DBBackup_Dir}/${BKPfile}.tar  *.*
gzip ${DBBackup_Dir}/${BKPfile}.tar
