#!/bin/bash
#set -x
# Usage of the file
if [[ $# -ne 5 ]]
then
 echo "THIS SCRIPT MUST BE RUN FROM DB2 SERVER USING DB2 INSTANCE ID"
 echo "Usage "
 echo $0 " --db=databasename --dbuser=exportuser --dbpassword=exportuserpassword --backupdir=Directory --bkpfile=bkpfilename"
 echo "Example " $0 " --db=wpcdb --dbuser=wpc1 --dbpassword=ibm4wpc --backupdir=/u01/backup --bkpfile=july10bkp"
 exit 0
fi

echo "THIS SCRIPT MUST BE RUN FROM DB2 SERVER USING DB2 INSTANCE ID"
# 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 -rf ${DBBackup_Dir}/${BKPfile}
mkdir -p ${DBBackup_Dir}/${BKPfile}
cd  ${DBBackup_Dir}/${BKPfile} 

# set the database character set
db2set DB2CODEPAGE=1208

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

# Create seqtab table to store sequence information
db2 -v "drop table seqtab" > insert_seq_values.log
db2 -v "create table seqtab (seqname varchar(30), latestval integer)" >> insert_seq_values.log
db2 -x "select 'insert into seqtab values ('||seqname||',nextval for '||seqname||');' from syscat.sequences where lower(SEQSCHEMA)='${DBUserName}'" >seqinsert.sql
echo "commit;" >> seqinsert.sql
sed -e "s/(/('/g" -e "s/,nextval/',nextval/g" seqinsert.sql > seqinsert1.sql
db2 -tvf seqinsert1.sql >> insert_seq_values.log

rm seqinsert.sql seqinsert1.sql

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

# Export the Data
db2move ${DBName} export -sn ${DBUserName} > export.log 

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

exit 0
