#!/bin/bash

# Copyright 2005, IBM Corporation

# Do report for all collaboration areas.


# Usage of the file
if [[ $# -ne 5 ]]
then
 echo "Usage "
 echo $0 " --db=databasename --dbuser=touser --dbpassword=touserpassword --code=cmp code --ctgname=SampleCiatalog"
 echo "Example " $0 " --db=wpcdb --dbuser=wpc1 --dbpassword=wpc1 --code=trigo --ctgname=testcatalog"

 exit 0
fi

curdir="`pwd`"
echo "Directory now is $curdir"
# Declare the variables
DBName=`echo $1 |cut -d "=" -f2`;export DBName
DBUSER=`echo $2 |cut -d "=" -f2`;export DBUSER
DBUserPassword=`echo $3 |cut -d "=" -f2`;export DBUserPassword
CMPCODE=`echo $4 | cut -d "=" -f2`;export CMPCODE
CATALOGNAME=`echo $5 | cut -d "=" -f2`;
# this is to handle CATALOGNAME with space inside, caller of this script 
# would encode the name by replacing space with ~
CATALOGNAME=`echo $CATALOGNAME | sed 's/~/ /g'`;
export CATALOGNAME

RepFile=`date |awk '{print "ghost_items_reports/report_"$2"_"$3"_"$6"_"$4}'|sed s/":"//g`;export RepFile

# Creating Logs Directory
mkdir -p ghost_items_reports

. ${TOP}/src/db/schema/util/set_db.sh --confirm_db=no
#Getting the company id for CMP CODE
${TOUCH} tmpcmpid.sql
${ECHO} "Getting company id for the $CMPCODE"
${CAT} $DB_SCRIPTS/get_cmpid_for_cmpcode.sql | ${SED} "s/%_CCD_CODE%/$CMPCODE/g" > tmpcmpid.sql
CMP_ID_QRY=`. ${TOP}/src/db/schema/util/run_db_cmd.sh --file=tmpcmpid.sql --errorfilter=yes | ${GREP} 'cmpid-'`
${ECHO} $CMP_ID_QRY
CMP_QRY_VAL="${CMP_ID_QRY}"
CMP_ID=`${ECHO} $CMP_QRY_VAL | ${GREP} 'cmpid-' | cut -f2 -d "-"`

#${ECHO} "Company Id found $CMP_ID"
if [ "$CMP_ID" != "" ];then
    ${ECHO} "company id found $CMP_ID"
    ${RM} tmpcmpid.sql
else
    ${ECHO} "company id not found. Exiting..."
    exit 0
fi
cd $curdir
db2 connect to ${DBName} user ${DBUSER} using ${DBUserPassword}
db2 "select coa_id from coa where COA_CONTAINER_TYPE='CATALOG' and COA_CMP_ID=$CMP_ID and COA_SRC_CONTAINER_ID IN(SELECT CTG_ID FROM CTG WHERE CTG_NAME='$CATALOGNAME' AND CTG_TYPE='CATALOG')" |grep -v COA_ID |grep -v "\-\-"|grep -v record > coaid.txt
db2 terminate

for CollabID in `cat coaid.txt`

do
echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo "Running report for Collab Area ID ${CollabID}"
echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"

. $TOP/src/integrity/oneCmp/workflow/db2/report_ghost_items_db2.sh --db=${DBName} --dbuser=${DBUSER} --dbpassword=${DBUserPassword} --collabid=${CollabID} --reportfile=${RepFile}_${CollabID}.txt

echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo "Report on Collab Area ID ${CollabID} is done"
echo "Look at file ${RepFile}_${CollabID}.txt for report"
echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"

done
mkdir -p $TOP/logs/ghost_items_reports
cd $curdir
mv ghost_items_reports/*.txt $TOP/logs/ghost_items_reports 2> /dev/null
exit $?
