#!/bin/bash
 #Usage of the script
if [[ $# -ne 3 ]]
then
   echo "Usage 1:";
   echo "wpcAnalyzer.sh --company=CompanyCode --groups=NumberOfGroups --defn=Metadata-Definition-parameter-file OR all";
   echo "Example: wpcAnalyzer.sh --company=40001 --groups=3 --defn="$TOP"/src/db/scripts/impl_analyzer/sample_definition.txt";
   echo;
   echo "Usage 2:";
   echo "wpcAnalyzer.sh --company=CompanyCode --groups=NumberOfGroups --rundate=existing_previous_rundate_in_metadata_table";
   echo "Example: wpcAnalyzer.sh --company=40001 --groups=3 --rundate=2007-01-06-03.52.27.000000";
   echo;
   echo "The order of arguments important!!!";
   exit 1;
fi

#/src/db/scripts/impl_analyzer/
BASE_PATH=$TOP"/src/db/scripts/impl_analyzer"
#BASE_PATH="/home/db2inst1/wpc_anal/scripts"
csv_file=$BASE_PATH"/WPC_Analyzer.csv"

# Extract the variables
companyCode=`echo $1 | cut -d "=" -f2`; export companyCode
groups=`echo $2 | cut -d "=" -f2`; export groups
thirdName=`echo $3 | cut -d "=" -f1`; export thirdName
thirdValue=`echo $3 | cut -d "=" -f2`; export thirdValue

# Validate input parameters
if [ ! $companyCode ]
 then companyCode=40001
 echo "Company defaulted to 40001"
fi

if [ ! $groups ]
 then groups=10
 echo "groups defaulted to 10"
elif (( $groups <= 0 )) ||  (($groups > 20)); then
 echo "Number of groups must be between 1 and 20"; exit 0
fi

echo $thirdName
if [[ ! $thirdName ]] || [[ ! $thirdValue ]] ; then
 echo "Third parm incorrect" $thirdName $thirdValue ; exit 0
elif ! [ $thirdName == "--rundate" ] &&  ! [ $thirdName == "--defn" ]; then
 echo "Third option incorrect" $thirdName ; exit 0
fi

. ${TOP}/bin/get_params.sh

. ${TOP}/src/db/schema/util/set_db.sh \
  --db_user_name=${_CCD_DB_USER_NAME} \
  --db_user_pwd=${_CCD_DB_USER_PWD} \
  --db_service_name=${_CCD_DB_SERVICE_NAME}
pwd
cnct_no_term=`echo $CONNECTION | cut -d";" -f1`
echo $cnct_no_term
db2 $cnct_no_term

cd $BASE_PATH

if [ $companyCode == 1 ]; then
  echo "Company not supported"; exit 0
fi

db2 "select 'company_name', cmp_company_name from cmp where cmp_company_id = $companyCode" > db2/tmp/cmp.out
cmp_rslt=`grep "record" db2/tmp/cmp.out|awk '{ print $1}'`
if [ ! $cmp_rslt ]; then
  echo "Error verifying company -- check company code"; exit 0
elif ! [ $cmp_rslt == 1 ]; then
  echo "Company not in cmp table"; exit 0
else
  company=`grep "company_name" db2/tmp/cmp.out|awk '{ print $2}'`
  echo $company
fi 

check_rundate() {
db2 "select 'run_date', timestamp('"$thirdValue"') from metadata_statistics where rundate='"$thirdValue"' fetch first 1 row only with ur" > db2/tmp/date.out
dt_rslt=`grep "record" db2/tmp/date.out|awk '{ print $1}'`
if [ ! $dt_rslt ]; then
  echo "Error verifying date -- check rundate"; exit 0
elif ! [ $dt_rslt == 1 ]; then
  echo "Rundate not exists"; exit 0
else
  rundate=`grep "run_date" db2/tmp/date.out|awk '{ print $2}'`
  echo $rundate
fi 
}

# Checking for Definition file or Rundate and set variables
if [ $thirdName == "--defn" ]; then
 all_var=`echo $thirdValue|tr a-z A-Z`
 if [ $all_var == "ALL" ]; then
   defn_file=$BASE_PATH"/db2/metadata_definition"
 elif ! [ -s $thirdValue ]; then
   echo $thirdValue "Not a valid file or zero size"; exit 0
 else
   defn_file=$thirdValue
 fi
 rundate=`date +%Y-%m-%d-%H.%M.%S.000000`
 echo "Rundate: "$rundate 
else
 #defn_file=$BASE_PATH"/db2/metadata_definition"
 check_rundate 
 echo "Analyzer start time: " `date`
fi

# Collect Statistics if option is Definition file
cd $BASE_PATH/db2
logfile="$BASE_PATH/db2/tmp/analyzer_log_"`date +%Y-%m-%d-%H.%M.%S`
if [ $thirdName == "--defn" ]; then 
  java_run_flag=1
  for i in `grep -v \# $defn_file` 
  do
   echo "Collecting statistics for " $i `date` >> $logfile
   echo "Collecting statistics for " $i `date` 
   if [ -s $i.sql ]; then
     sed -e "s/current timestamp/\'"$rundate"\'/g" -e 's/40001/'$companyCode'/g' $i.sql > tmp/ins_$i.sql
     db2 -txf tmp/ins_$i.sql >> $logfile
   else
     if [ $i == "AttributesPerItem" ] || [ $i == "LocationAttributesPerItem" ]; then
        if [ $java_run_flag = 1 ]; then
          echo "running java..."
          $JAVA_RT com.ibm.ccd.content.common.ItemAnalyzer $companyCode $rundate >> $logfile
          java_run_flag=0
        fi
     else
       echo "SQL file not found for " $i
     fi
   fi
  done
fi

# Write CSV file headers
echo "Company_Code,"$companyCode > $csv_file
echo "Company_Name,"$company >> $csv_file
echo "Run_date,"$rundate >> $csv_file

cd $BASE_PATH/db2

# Change rundate and number of groups in totals and group size query
sed -e "s/2007-01-01-11.11.11.000000/"$rundate"/g" -e 's/\/10/\/'$groups'/g' defn_totals_grp_size.sql > tmp/defn_totals4rundt.sql

# execute group size query
db2 -txf tmp/defn_totals4rundt.sql > tmp/defn_totals_size
if [ $thirdName == "--rundate" ]; then
  awk '{print $1}' tmp/defn_totals_size > $BASE_PATH/db2/tmp/defn_file4rundate
  defn_file=$BASE_PATH"/db2/tmp/defn_file4rundate"
fi
  

# csv file details for groups=1 and groups=n are merged here
append_csv_file() {
  size=`grep ^$defn db2/tmp/defn_totals_size | cut -d"-" -f2 | cut -d"." -f1`
  totals=`grep ^$defn db2/tmp/defn_totals_size | cut -d"-" -f3 `
  if [ ! $totals ] ; then
    totals=0 ; size=0 ; avg_string=0
  fi 
  echo $company",Total_for_"$defn","$totals >> $csv_file
  echo $company",Number_of_distribution_groups,"$groups >> $csv_file
  echo $company",Group_size_for_"$defn","$size >> $csv_file
  part1=`echo $defn|sed -e 's/Per/:/g'|cut -d":" -f1`
  part2=`echo $defn|sed -e 's/Per/:/g'|cut -d":" -f2`
  if [ $size == 0 ]; then 
    echo $company",Number_of_"$part1"_for_"$part2","$avg_string >> $csv_file
  else
    echo $company",Average_"$part1"_for_"$part2"_per_group,"$avg_string >> $csv_file
  fi
}

finish_script_with_display() {
 echo "PATH_variable,"$PATH >> $csv_file
 cat $TOP/etc/default/common.properties >> $csv_file
 echo "Analyzer finish time: " `date`
 echo "Please check log file for any errors: " $logfile
 echo "Output csv file: " $csv_file
}

# Calculating single average when groups=1
if [ $groups == 1 ]; then
  cd ..
  for defn in `grep -v \# $defn_file`
  do
    avg_string=`grep ^$defn db2/tmp/defn_totals_size | cut -d"-" -f4 | cut -d"." -f1`
    append_csv_file
  done
  finish_script_with_display
  exit 0
fi  

# Change rundate and number of groups in group average queries 
sed -e "s/2007-01-01-11.11.11.000000/"$rundate"/g" tail_template > qry_tail 
sed -e "s/2007-01-01-11.11.11.000000/"$rundate"/g" small_defn_template > small_defn_listing.sql 

build_case_structure() {
   i=1 ; a=1 ; ext=0 ; case_str=" " 
   while [ $ext -eq 0 ]
   do
     if [ $i == $groups ]; then 
       b=$totals
       case_str=$case_str"  else "$i
       #echo $case_str
     else 
       ((b = $size * $i)) 
       case_str=$case_str" when order_sequence between "$a" and "$b" then "$i
       #echo $case_str
     fi
     #echo  $a " and " $b " then " $i
     ((a = $b + 1)) 
     (( i++ ))
     if (( $i >  $groups )) || (( $a > $totals ));
       then ext=1
     fi
   done
}

# Build group average query for each Metadata Definition 
for defn in `awk '{print $1}' tmp/defn_totals_size`
do 
  #echo $defn
  size=`grep ^$defn tmp/defn_totals_size | cut -d"-" -f2 | cut -d"." -f1`
  totals=`grep ^$defn tmp/defn_totals_size | cut -d"-" -f3 `
  #echo "size = " $size "groups = " $groups "total = " $totals
  case_str=" "
  if [ $totals -gt $groups ]; then 
     build_case_structure
     echo $case_str" end as dist_groups, " > tmp/case_string
     cat qry_head tmp/case_string qry_tail | sed -e 's/SizePerScript/'$defn'/g' > tmp/final_qry_$defn
     #echo $case_str
  else 
     echo $defn "Totals < groups: All entries will be listed" >> $logfile
     sed -e 's/SizePerScript/'$defn'/g' small_defn_listing.sql > tmp/final_qry_$defn
  fi
done

averages_with_commas() {
avg_string=""
i=1
for j in `awk '{print $2}' db2/tmp/final_list_$defn`
do
 if [ $i == 1 ]; then
   avg_string=$avg_string$j
 else
   avg_string=$avg_string","$j
 fi
 ((i++))
done
 #echo $avg_string
}

cd ..
# Write analyzer details to csv file for each given definition
#echo $defn_file
for defn in `grep -v \# $defn_file`
do
  #echo "final_list" $defn
  if [ -s db2/tmp/final_qry_$defn ]; then 
    db2 -txf db2/tmp/final_qry_$defn > db2/tmp/final_list_$defn
    averages_with_commas
  fi
  append_csv_file
done

finish_script_with_display
exit 0
