#-----------------------------------README------------------------------------------------
# Shell for Auto Validation of NV production mode. 
# For Flow of the prog, check main function at line 305.
#-----------------------------------------------------------------------------------------

. $HPD_ROOT/bin/nr_db_utils
. $HPD_ROOT/bin/nr_mongodb_utils

NV_BOOTSTRAP_DEFAULT_MAX_AGE=60480
CONFIG_DEFAULT_MAX_AGE=604800
CAV_NV_DEFAULT_MAX_AGE=7200
FAILURE=0
MONGO_KEYWORD=`grep "^MONGODB_SERVER" $HPD_ROOT/conf/hpd.conf |awk -F " " '{print $2}'`
RUM_CONF="$HPD_ROOT/rum/config/rum.conf"
RUM_CLIENT_ID=`grep "^RUM_CLIENT_ID" $RUM_CONF |awk -F " " '{print $2}'`

get_mongo_details()
{
db_details=$(cat  $HPD_ROOT/conf/hpd.conf|grep -e "^MONGODB_SERVER");
if [[ "X$db_details" == "X" ]]; then
   echo -e "\e[1;33mWARNING: Mongo server Keyword  is Disabled in hpd.conf file. Please enable it.\e[0m "
   exit 0
fi


#making of connection string which have format --> "mongodb://username:password@hostip:port/dbname"
                                                                  #from line -->
                                                                  #MONGODB_SERVER <enable/disable> <ip> <port> <dbname> <username> <passowrd>"
                                                                  #which is present in hpd.conf file

hostip=$(echo $db_details|grep -e MONGODB_SERVER|cut -d ' ' -f 3);
port=$(echo $db_details|grep -e MONGODB_SERVER|cut -d ' ' -f 4);
dbname=$(echo $db_details|grep -e MONGODB_SERVER|cut -d ' ' -f 5);
username=$(echo $db_details|grep -e MONGODB_SERVER|cut -d ' ' -f 6);
password=$(echo $db_details|grep -e MONGODB_SERVER|cut -d ' ' -f 7 );
}


if [ ! -z ${MONGO_KEYWORD=} ]; then
  prodMode=$(run_mongo_query \
    "db.RUM_CONFIG_${RUM_CLIENT_ID}.find({}, {NV_PROD_MODE:1}).pretty()" \
    | grep "NV_PROD_MODE" \
    | awk '{gsub("\"","",$0);print $0}' \
    | awk -F "," '{print $2}' \
    | awk -F ":" '{print $2}' \
    | awk '{print $1}')
else
  prodMode=`grep "^NV_PROD_MODE" $RUM_CONF | cut -d ' ' -f2`
fi
if [ "X$prodMode" == "X" ]; then
 prodMode=1
fi



JSFILES="config.js cav_nv.js nv_bootstrap.js jquery.min.js"

check_prod_mode(){
if [ -d ${prodMode} ]; then
   #echo -e "Production Mode is Set [ \e[1;31m\xE2\x9D\x8C \e[0m ]"
   #echo -e "\e[1;33mWARNING: Keyword NV_PROD_MODE is Not Present in rum.conf file.To run the this tool please Add it.\e[0m"
   exit 0
fi
if [ $prodMode -eq 0 ]; then 
   #echo -e "Production Mode is Set [ \e[1;31m\xE2\x9D\x8C \e[0m ]"
   #echo -e "\e[1;33mWARNING: Keyword NV_PROD_MODE is Disabled in rum.conf file.To run the this tool please enable it.\e[0m "
   exit 0
else 
  #echo -e "Production Mode is Set [ \e[1;32m\xE2\x9C\x94 \e[0m ] "
  echo "Production Mode is Set,Executing prod validation checks....."
fi
}


keyword_check()
{
  check_hpd_debug=`grep -w "^HPD_DEBUG" $HPD_ROOT/conf/hpd.conf | cut -d ' ' -f2`
  check_progress_enabled=`grep "^PROGRESS_ENABLED" $HPD_ROOT/conf/hpd.conf | cut -d ' ' -f3`
  check_hpd_monitor=`grep "^HPD_MONITOR" $HPD_ROOT/conf/hpd.conf | cut -d ' ' -f2`
  check_prog_msec=`grep "^PROGRESS_MSECS" $NS_WDIR//workspace/admin/default/cavisson/default/default/scenarios/nv.conf | cut -d ' ' -f2`
  if [ "X$check_prog_msec" == "X" ]; then
    check_prog_msec=60000
  fi
	if [ "X${check_hpd_monitor}" == "X" ]; then
		check_hpd_monitor=1
	fi

#------------------------To Check HPD_DEBUG keyword is enabled or not-----------------------
if [[  "X${check_hpd_debug}" == "X" || $check_hpd_debug -eq 0 ]]; then
   echo -e "HPD_DEBUG is OFF [ \e[1;32m\xE2\x9C\x94 \e[0m ]"
else
   echo -e "HPD_DEBUG is OFF [ \e[1;31m\xE2\x9D\x8C \e[0m ]"
   FAILURE=1
   echo -e "\e[1;33m WARNING: Keyword HPD_DEBUG is ENABLED.Please disable it \e[0m"
fi
#-----------------------To Compare the values of PROGRESS_ENABLED and PROGRESS_MSECS------------
if [ "X$check_progress_enabled" == "X" ];then
   FAILURE=1
   echo -e "PROGRESS_ENABLED value = PROGRESS_MSECS value [ \e[1;31m\xE2\x9D\x8C \e[0m ]"
   echo -e "\e[1;33m WARNING: PROGRESS_ENABLED is not Present in hpd.conf. \e[0m"
elif [ "X$check_prog_msec" == "X" ];then
   FAILURE=1
   echo -e "PROGRESS_ENABLED value = PROGRESS_MSECS value [ \e[1;31m\xE2\x9D\x8C \e[0m ]"
   echo -e "\e[1;33m WARNING: PROGRESS_MSECS is not Present in nv.conf. \e[0m"
else
   if [ "X$check_progress_enabled" == "X$check_prog_msec" ]; then
      echo -e "PROGRESS_ENABLED value = PROGRESS_MSECS value [ \e[1;32m\xE2\x9C\x94 \e[0m ]"
   else
      echo -e "PROGRESS_ENABLED value = PROGRESS_MSECS value [ \e[1;31m\xE2\x9D\x8C \e[0m ]"
      echo -e "\e[1;33m WARNING: Value of PROGRESS_ENABLED & PROGRESS_MSECS are not same. \e[0m"
      FAILURE=1
   fi
fi
#--------------To Check HPD_MONITOR keyword is enabled or not---------------------
if [ "X${check_hpd_monitor}" == "X" ]; then
   FAILURE=1
   echo -e "HPD_MONITOR Enabled [ \e[1;31m\xE2\x9D\x8C \e[0m ]"  
   echo -e "\e[1;33m WARNING: Keyword HPD_MONITOR IS Not Present in hpd.conf \e[0m"
else
   if [ $check_hpd_monitor -eq 0 ]; then
      echo -e "HPD_MONITOR Enabled [ \e[1;31m\xE2\x9D\x8C \e[0m ]" 
      echo -e "\e[1;33m WARNING: Keyword HPD_MONITOR IS Not ENABLED,please Enable it \e[0m"
      FAILURE=1
   elif [ $check_hpd_monitor -eq 1 ]; then
      echo -e "HPD_MONITOR Enabled [ \e[1;32m\xE2\x9C\x94 \e[0m ]" 
   fi
fi 
#-------------------------------------------------------------------
#Check all config, nv_bootstrap and cav_nv.js file. and validate them if those are compressed, minified and cached enabled.
for file in ${JSFILES[*]}
do
  filepath=`cd $HPD_ROOT/real && find . -name $file`
  for fpath in ${filepath[*]}
  do
    filename="${fpath##*/}" # get filename
    dirname="${fpath%/*}" # get directory/path name
    relative_file_name=$filename
    relative_dir_name=`echo $dirname | sed 's/.*\(default\)/\1/g'`
    if [ "X$relative_file_name" == "Xconfig.js" ];then
       max_age=$CONFIG_DEFAULT_MAX_AGE
    elif [ "X$relative_file_name" == "Xcav_nv.js" ];then
       max_age=$CAV_NV_DEFAULT_MAX_AGE
    else
       max_age=$NV_BOOTSTRAP_DEFAULT_MAX_AGE
    fi
    #check if control file is present.  .
    if [[ ! -e $HPD_ROOT/control/$relative_dir_name/$relative_file_name ]];then
       #echo "Control File Setting :"
       echo -e "Control file for real/$relative_dir_name/$relative_file_name [ \e[1;31m\xE2\x9D\x8C \e[0m ]"
       mkdir -p /$HPD_ROOT/control/$relative_dir_name
       echo -e  "COMPRESSION_TYPE gzip\nCONTENT_MINIFY\nHEADER cache-control: public, max-age=$max_age" >> $HPD_ROOT/control/$relative_dir_name/$relative_file_name
       echo -e "\e[1;34m INFO: Added control/$relative_dir_name/$relative_file_name. \e[0m"
    else
       grep "COMPRESSION_TYPE.*" $HPD_ROOT/control/$relative_dir_name/$relative_file_name>/dev/null
       check_compres=$?
       if [ $check_compres -eq 1 ]; then
          echo -e "COMPRESSION_TYPE gzip" >> $HPD_ROOT/control/$relative_dir_name/$relative_file_name
          echo "real/$relative_dir_name/$relative_file_name - Added COMPRESSION_TYPE Header in control file."
       fi
       grep "CONTENT_MINIFY.*" $HPD_ROOT/control/$relative_dir_name/$relative_file_name >/dev/null
       check_content=$?
       if [ $check_content -eq 1 ]; then
          echo "CONTENT_MINIFY" >> $HPD_ROOT/control/$relative_dir_name/$relative_file_name
          echo "real/$relative_dir_name/$relative_file_name - Added CONTENT_MINIFY Header in control file."
       fi
       grep "HEADER.*" $HPD_ROOT/control/$relative_dir_name/$relative_file_name>/dev/null
       check_header1=$?
       if [ $check_header1 -eq 1 ]; then
          echo "HEADER cache-control: public, max-age=$max_age" >>$HPD_ROOT/control/$relative_dir_name/$relative_file_name
          echo "real/$relative_dir_name/$relative_file_name - Added HEADER cache-control in control file."
       fi
       grep "^#HEADER.*" $HPD_ROOT/control/$relative_dir_name/$relative_file_name>/dev/null
       check_header2=$?
       if [ $check_header2 -eq 0 ]; then
          sed -i "s/#HEADER cache-control.*/HEADER cache-control: public, max-age=$max_age/g" $HPD_ROOT/control/$relative_dir_name/$relative_file_name
          echo "real/$relative_dir_name/$relative_file_name -  Added HEADER cache-control in control file."
       fi
    fi
  done
done
}
#-----------------------------------------------------------------------------------------------------
cache_Setting()
{
echo "Cache Setting :"
for file in ${JSFILES[*]}
do
  filepath=`cd $HPD_ROOT/real && find . -name $file`
  for fpath in ${filepath[*]}
  do
    filename="${fpath##*/}" # get filename
    dirname="${fpath%/*}" # get directory/path name
    
    relative_file_name=$filename
    relative_dir_name=`echo $dirname | sed 's/.*\(default\)/\1/g'`
    if [ "X$relative_file_name" == "Xconfig.js" ];then
       def_max_age=$CONFIG_DEFAULT_MAX_AGE
    elif [ "X$relative_file_name" == "Xcav_nv.js" ];then
       def_max_age=$CAV_NV_DEFAULT_MAX_AGE
    else
       def_max_age=$NV_BOOTSTRAP_DEFAULT_MAX_AGE
    fi
    #
    maxage=`grep "max-age" $HPD_ROOT/control/$relative_dir_name/$relative_file_name | cut -d '=' -f2`
    if [ -d ${maxage} ]; then
      sed -i "s/max-age=.*/max-age=$def_max_age/g" $HPD_ROOT/control/$relative_dir_name/$relative_file_name
      echo -e "   real/$relative_dir_name/$relative_file_name- was not configured,modified to $def_max_age [ \e[1;32m\xE2\x9C\x94 \e[0m ]"
    else
      echo -e "   real/$relative_dir_name/$relative_file_name [ \e[1;32m\xE2\x9C\x94 \e[0m ]"
    fi
  done
done
}
#-------------------------------------------------------
compr_Setting(){
echo "Compression Setting :"
for file in ${JSFILES[*]}
do
  filepath=`cd $HPD_ROOT/real && find . -name $file`
  for fpath in ${filepath[*]}
  do
    filename="${fpath##*/}" # get filename
    dirname="${fpath%/*}" # get directory/path name
    
    relative_file_name=$filename
    relative_dir_name=`echo $dirname | sed 's/.*\(default\)/\1/g'`
    compr_type=`grep "^COMPRESSION_TYPE" $HPD_ROOT/control/$relative_dir_name/$relative_file_name | cut -d ' ' -f2`
    cont_minify=`grep "^CONTENT_MINIFY" $HPD_ROOT/control/$relative_dir_name/$relative_file_name`
    if [[ "X${compr_type}" == "X" || "X${cont_minify}" == "X" ]]; then
      sed -i "s/#COMPRESSION_TYPE.*/COMPRESSION_TYPE/g" $HPD_ROOT/control/$relative_dir_name/$relative_file_name
      sed -i "s/COMPRESSION_TYPE.*/COMPRESSION_TYPE gzip/g" $HPD_ROOT/control/$relative_dir_name/$relative_file_name
      sed -i "s/#CONTENT_MINIFY.*/CONTENT_MINIFY/g" $HPD_ROOT/control/$relative_dir_name/$relative_file_name 
      echo -e "   real/$relative_dir_name/$relative_file_name- was not configured,modified to gzip and minify [ \e[1;32m\xE2\x9C\x94 \e[0m ]"
    else
      echo -e "   real/$relative_dir_name/$relative_file_name [ \e[1;32m\xE2\x9C\x94 \e[0m ]"
    fi
  done
done
}
#-----------------------------
node_name=0
INIT_FILE=/tmp/init_file.csv
TMP_FILE=/tmp/demo_slave.csv
DEV_NULL=/dev/null

init_setup()
{
command="\copy nvclustertable_$RUM_CLIENT_ID to '$TMP_FILE' with delimiter '|' null as ''";
 `psql  $CON_STRING -c "$command" >/tmp/statusrep_$$.txt`


#check for status
if [ $? -eq 0 ];then
echo "Copied Successfully" > /tmp/initfile1_$$.txt
fi

CUR_NODEID=`cat $HPD_ROOT/rum/.slaveid 2>$DEV_NULL`
while read line
do
HPD_IP=`echo $line |cut -d "|" -f 5`
NODE_ID=`echo $line | cut -d "|" -f2`
NODE=`echo $line |cut -d "|" -f 3`
CONTROLLER_NAME=`echo $line |cut -d "|" -f 11`
check_arr[$node_name]=$NODE
node_name=`expr $node_name + 1`
controller_list[$counter1]=$CONTROLLER_NAME
machine_list[$counter1]=$HPD_IP
node_list[$counter1]=$NODE 
if [ "X$CUR_NODEID" == "X$NODE_ID" ];then
   CUR_NODE_NAME=$NODE
   #echo $CUR_NODE_NAME
fi
counter1=`expr $counter1 + 1`
done <$TMP_FILE
rm $TMP_FILE
#---------------------------------Current node-------------------------
#echo "Checking Current node.........."
for(( i = 0; i < $counter1; i++ ))
do
 #cur_node=`grep "^NV_PROD_MODE" $HPD_ROOT/rum/config/rum.conf |awk -F " " '{print $2}'`
 if [ "X${node_list[$i]}" == "X$CUR_NODE_NAME"  ];then
   cur_node=${controller_list[$i]}
   #break
 #else
   #exit 0
 fi
  
done 
#-----current node build------------------------------------
TMP_FILE=$HPD_ROOT/.tmp/buildver_$$
nsu_get_version > $TMP_FILE
buildver_curnode=`grep "^NetStorm:Version" $TMP_FILE |awk -F " " '{print $2}'`
buildnum_curnode=`grep "^NetStorm:Version" $TMP_FILE |awk -F " " '{print $4}'`
rm $TMP_FILE
}
#-------------------To show build version--------------------------

build_ver=
build_num=
show_build_version()
{
echo "   Build version of other nodes are as follows:"
for (( i = 0; i < $counter1; i++ ))
do
#build_ver[$i]=`grep "^NetStorm:Version" $HPD_ROOT/bin/buildver_$i |awk -F " " '{print $2}'`
#build_num[$i]=`grep "^NetStorm:Version" $HPD_ROOT/bin/buildver_$i |awk -F " " '{print $4}'`
#if [ $buildver_curnode != ${build_ver[$i]} -o $buildnum_curnode != ${build_num[$i]} ]; then
  if [ "X${node_list[$i]}" != "X$CUR_NODE_NAME"  ];then
      echo "   ${controller_list[$i]} : ${build_ver[$i]} (${build_num[$i]}"
  fi
done
}
#-------------------To check build version--------------------------
check_build_version()
{
echo "Checking BuildVersion.........."
for(( i = 0; i < $counter1; i++ ))
do
  mkdir -p $HPD_ROOT/.tmp
  TMP_FILE=$HPD_ROOT/.tmp/buildver_$$
  # This shell will internally run cluster controller tool and check all the build version of the nodes.
  nsi_cluster_control -o build -n ${node_list[$i]}>$TMP_FILE
  build_ver[$i]=`grep "^NetStorm:Version" $TMP_FILE |awk -F " " '{print $2}'`
  build_num[$i]=`grep "^NetStorm:Version" $TMP_FILE |awk -F " " '{print $4}'`
  rm $TMP_FILE
done

for (( i = 0; i < $counter1; i++ ))
do
  if [ $buildver_curnode != ${build_ver[$i]} -o $buildnum_curnode != ${build_num[$i]} ]; then
     flag=1
     break
  else
     flag=0
  fi
done
#
if [ $flag -eq 1 ];then
   echo -e "   Build are in sync [ \e[1;31m\xE2\x9D\x8C \e[0m ]"
   FAILURE=1
   echo -e "\e[1;33m   WARNING: Build version of the nodes are not in sync.Detailed error - \e[0m"
   echo "   Current node :- $cur_node"
   echo "   Build version of Current node : $buildver_curnode ($buildnum_curnode "
   show_build_version
else
   echo -e "   Build are in sync [ \e[1;32m\xE2\x9C\x94 \e[0m ]"
fi
}

check_rum()
{
  echo "Checking rum.conf file in all nodes.........."
  #For rum.conf comparision,this will run compareRumSetting.sh shell.
  $HPD_ROOT/bin/./compareRumSetting.sh
  
}
#----------------------main-------------------
main(){
   check_prod_mode
   keyword_check
   cache_Setting
   compr_Setting
#---cluster check---
grep "^HPD_CLUSTER*" $HPD_ROOT/conf/hpd.conf >/dev/null
check_cluster=$?
if [ $check_cluster -eq 0 ]; then
	 init_setup
   check_build_version
   check_rum
 else
	 echo -e "\e[1;33m   WARNING: Keyword comparison and build version can be validate only in case of cluster, so ignoring these checks \e[0m"
fi
if [ $FAILURE -eq 1 ]; then
  echo "ERROR: Prod Validation checks failed, Aborting. "
  exit -1 #hpd stop
else
  echo "SUCCESS: Prod Validation checks successful."
  exit 0
fi
}
main
