#!/bin/bash

cd /u1/Operation_log/

##format log
for i in `ls -l | awk '{if(NR==1)next;print $NF}'`
do 
   cat $i | perl -pe 's/\e([^\[\]]|\[.*?[a-zA-Z]|\].*?\a)//g' | col -b > /home/Operation_filter_log/clean/$i
done

###--------------------------------------------------------###

##normal commmand
cd /home/Operation_filter_log/clean/

for j in `ls -l | awk '{if(NR==1)next;print $NF}'`
do
   egrep "Script|@$HOSTNAME" $j > /home/Operation_filter_log/normal/$j.txt
done

##dangerous commmand
#if [ "$(ls -A /home/Operation_filter_log/dangerous/)" != "" ];then

#ls -l /home/Operation_filter_log/dangerous/ | awk '{if(NR==1)next;print $NF}' > /root/list.txt

cd /home/Operation_filter_log/normal/
for k in `ls -l | awk '{if(NR==1)next;print $NF}'`
do 
   file1=`ls -l /home/Operation_filter_log/dangerous/$k |awk '{print $5}'`
   egrep -w 'rm|reboot|shutdown|init|poweroff|passwd|mkfs|kill|pkill|stop|clusvcadm|fence_drac|fence_ipmilan' $k > /dev/null
   
if [ "$?" = "0" ];then
   egrep -w "Script|@$HOSTNAME|rm|reboot|shutdown|init|poweroff|passwd|mkfs|kill|pkill|stop|clusvcadm|fence_drac|fence_ipmilan" $k > /home/Operation_filter_log/dangerous/$k
   ls -l /home/Operation_filter_log/dangerous/ | awk '{if(NR==1)next;print $NF}' > /root/list.txt        
   file2=`ls -l /home/Operation_filter_log/dangerous/$k |awk '{print $5}'`

else
   exit 2
fi
done
      
if [ "$file1" != "$file2" ];then 
   for u in `awk -F"$HOSTNAME-|-" '{print $2}' /root/list.txt|sort -u` 
   do
      content=(`grep "$u" /root/list.txt`)
      content_LEN=${#content[@]}
      i=0
      while [ $i -lt $content_LEN ]
      do
      /usr/local/mysql/bin/mysql -h 192.168.177.66 -uxxx -pxxx -P3306 mon -e "insert into operation_log(hostname,user,execution_time,content) values('$HOSTNAME','$u',now(),'`cat /home/Operation_filter_log/dangerous/${content[$i]}`');"
      let i++
      done
   done
fi