#!/bin/sh

minute=0
hour=1
day=2
month=3

divisor=(60 24 31 12)

#Single generic function to handle all kinds of data and range
#Params: type(minute, hour, day, month)
get_data() 
{
        Error=0
	range=$1
	category=$2
	start=`cat "$2_marker"`
	end=`expr $start + $1 - 1`
	join_file="join_file_""$range""_""$category"
	op_file="disp_$range""_""$category"
	cat /dev/null > $join_file
        cat /dev/null > $op_file
	x='eval echo "\$$2"'
	y=`eval $x`
	div=${divisor[$y]}
	for i in $(seq $start $end)
	do 
		k=`expr $i % $div`
		cat $join_file > temp_$category
		srmd_file="srmd_""$category""_""$k"
                if [ -s "$SRMD_DIR/$srmd_file" ];then
                        #echo "$_file has some data."
                        join temp_$category $srmd_file   -a 1 -a 2  > $join_file 2> /dev/null
                else
                        Error=1
                        break
                fi

	done		
	#Collate data for $range $categories
        if [ "$Error" -eq 0 ]; then
	awk -v range=$range '{x=0;for(i=2;i<(range+2); ++i) x+=$i; {printf("%s \t\t %.2f\n", $1, x/range)}}' $join_file > $op_file
        fi
	rm -f temp_$category 
}

gen_pid_file() 
{
	cat /dev/null > pid_file
	IFS='^'
	for word in $1
	do
		for i in $word
		do
			echo -n "$i " >> pid_file
		done
	done	
	echo "" >> pid_file
}

#Show data for days, last one month, last 5 months, last 10 months, last 1 year
show_months() 
{
	cd $SRMD_DIR
	latest_1_day=`cat month_marker`
	get_data 5 month
	get_data 10 month
	get_data 12 month

	#Extract the pids and the process names
	WORD=`join  -a 1 -a 2 srmd_day_$latest_1_day disp_5_month 2> /dev/null | join -a 1 -a 2  - disp_10_month 2> /dev/null | join -a 1 -a 2 - disp_12_month 2> /dev/null | awk '{print $1}'`
	gen_pid_file "$WORD"
	echo "   PID  Process          1m     5m      10m      1y"
	echo "---------------------------------------------------"
	join -a 1 -a 2 srmd_day_$latest_1_day disp_5_month 2> /dev/null  \
			|join -a 1 -a 2 - disp_10_month 2> /dev/null  | join -a 1 -a 2 - disp_12_month 2> /dev/null | paste pid_file - \
			| awk '$1>0 {printf ("%6d %-16s %.2f\t%.2f\t%.2f\t%.2f\n", $1, $2, $4, $5, $6, $7)}'
}

#Show data for days, last one day, last 5 days, last 10 days
show_days() 
{
	cd $SRMD_DIR
	latest_1_day=`cat day_marker`
	get_data 3 day

	#Extract the pids and the process names
	WORD=`join  srmd_day_$latest_1_day disp_3_day  2> /dev/null | awk '{print $1}'`
	gen_pid_file "$WORD"
	echo "   PID  Process          1d     3d   " 
	echo "-------------------------------------"
	join -a 1 -a 2  srmd_day_$latest_1_day disp_3_day 2> /dev/null \
			| paste pid_file - \
			| awk '$1>0 {printf ("%6d %-16s %.2f\t%.2f\n", $1, $2, $4, $5)}'
}

#Show data for hours, display the last hour, last 5 hours and last 10 hours
show_hours() 
{
	cd $SRMD_DIR
	latest_1_hr=`cat hour_marker`
	get_data 5 hour
	get_data 10 hour
	
	#Extract the pids and process names
	WORD=`join  srmd_hour_$latest_1_hr disp_5_hour  2> /dev/null | join  - disp_10_hour 2> /dev/null | awk '{print $1}'`
	gen_pid_file "$WORD"
	echo "   PID  Process          1hr    5hr     10 hr"
	echo "----------------------------------------------"
	join -a 1 -a 2 srmd_hour_$latest_1_hr disp_5_hour 2> /dev/null \
			| join - disp_10_hour 2> /dev/null | paste pid_file - \
			| awk '$1>0 {printf ("%6d %-16s %.2f\t%.2f\t%.2f\n", $1, $2, $4, $5, $6);}'
		
}

#Handle default options, display the last 1 min, 5mins, 15mins, 1hr, 5hr and 72hr 
show_default () 
{
	cd $SRMD_DIR
	latest_1_min=`cat minute_marker`
	latest_1_hour=`cat hour_marker`
	get_data 5 minute
	get_data 15 minute
    get_data 1 hour
    get_data 5 hour
    get_data 24 hour
#    get_data 72 hour
    get_data 3 day
       
    join -a 1 -a 2  srmd_minute_$latest_1_min  disp_5_minute 2> /dev/null \
	 	| join -a 1 -a 2  - disp_15_minute 2> /dev/null | join -a 1 -a 2  - srmd_hour_$latest_1_hour 2> /dev/null \
        | join -a 1 -a 2  - disp_5_hour 2> /dev/null | join -a 1 -a 2  - disp_24_hour 2> /dev/null | join -a 1 -a 2  - disp_3_day > join_tmp_1 2> /dev/null

    #Extract the pids and process names
	WORD=`cat join_tmp_1 | awk '{print $1}'`
	gen_pid_file "$WORD"

	#Display the pids in a format
    cat join_tmp_1 | awk '{printf("%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n",$2, $3, $4, $5, $6, $7, $8)}' > join_tmp_2
	awk 'NR==FNR{a[i++]=$0};{b[x++]=$0;};{k=x-i};END{for(j=0;j<i;) print a[j++],b[k++]}' pid_file join_tmp_2 \
	| awk '$1>0 {printf("%07d %-16s %.2f %.2f %.2f %.2f %.2f %.2f %.2f\n",\
		$1, $2, $3, $4, $5, $6, $7, $8, $9)}'
    #rm -f join_tmp_1
}

show_cpu_utilz()
{
    if [ $1 -eq 0 ];then
    /usr/bin/vmstat 1 3 | /usr/bin/tail -n +5 | /bin/awk '{printf "Current:   %.2f%% (user procs:%.2f%%, system-kernel:%.2f%%, iowait:%.2f%%)\n", 100-$15, $13, $14, $16}'
    fi
    
    if [ $1 -eq 1 ]; then
        cd $SRMD_DIR
	    latest_1_min=`cat minute_marker`
	    latest_1_hour=`cat hour_marker`
	    get_data 5 minute
	    get_data 15 minute
        get_data 1 hour
        get_data 5 hour
        get_data 24 hour
       #get_data 72 hour
	get_data 3 day
        
        join -a 1 -a 2  srmd_minute_$latest_1_min  disp_5_minute 2> /dev/null \
	 	    | join -a 1 -a 2  - disp_15_minute 2> /dev/null | join -a 1 -a 2  - srmd_hour_$latest_1_hour 2> /dev/null \
            | join -a 1 -a 2  - disp_5_hour 2> /dev/null | join -a 1 -a 2 - disp_24_hour 2> /dev/null | join -a 1 -a 2  - disp_3_day > join_tmp_1 2> /dev/null

        #Extract the pids and process names
	    WORD=`cat join_tmp_1 | awk '{print $1}'`
	    gen_pid_file "$WORD"

        cat join_tmp_1 | awk '{printf("%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n",$2, $3, $4, $5, $6, $7, $8)}' \
            | paste pid_file - | awk '$1=="0000000" {printf("%-6d %-16s %.2f %.2f %.2f %.2f %.2f %.2f %.2f\n",\
                                      $1, $2, $3, $4, $5, $6, $7, $8, $9)}' > join_tmp_2
        
        cat join_tmp_2 | awk '{printf("%s\t",$3)}' | /bin/awk '{printf "1 minute:  %.2f%% (user procs:%.2f%%, system-kernel:%.2f%%, iowait:%.2f%%)\n", $1, $4, $3, $2}'
        cat join_tmp_2 | awk '{printf("%s\t",$4)}' | /bin/awk '{printf "5 minute:  %.2f%% (user procs:%.2f%%, system-kernel:%.2f%%, iowait:%.2f%%)\n", $1, $4, $3, $2}'
        cat join_tmp_2 | awk '{printf("%s\t",$5)}' | /bin/awk '{printf "15 minute: %.2f%% (user procs:%.2f%%, system-kernel:%.2f%%, iowait:%.2f%%)\n", $1, $4, $3, $2}'
        cat join_tmp_2 | awk '{printf("%s\t",$6)}' | /bin/awk '{printf "1 hour:    %.2f%% (user procs:%.2f%%, system-kernel:%.2f%%, iowait:%.2f%%)\n", $1, $4, $3, $2}'
        cat join_tmp_2 | awk '{printf("%s\t",$7)}' | /bin/awk '{printf "5 hour:    %.2f%% (user procs:%.2f%%, system-kernel:%.2f%%, iowait:%.2f%%)\n", $1, $4, $3, $2}'
        cat join_tmp_2 | awk '{printf("%s\t",$8)}' | /bin/awk '{printf "24 hour:   %.2f%% (user procs:%.2f%%, system-kernel:%.2f%%, iowait:%.2f%%)\n", $1, $4, $3, $2}'
        cat join_tmp_2 | awk '{printf("%s\t",$9)}' | /bin/awk '{printf "72 hour:   %.2f%% (user procs:%.2f%%, system-kernel:%.2f%%, iowait:%.2f%%)\n", $1, $4, $3, $2}'    
        #rm -f join_tmp_1
        #rm -f join_tmp_2
   fi
}

show_core_info () 
{
	cd $SRMD_DIR
 	latest_1_sec=`cat second_marker`
 	ncores=`grep processor /proc/cpuinfo| wc -l|awk '{printf("%d",$1);}'`
 	get_data $1 $2
 	op_file="disp_$1""_""$2"
 	join_file="join_file_""$1""_""$2"

 	#Extract the pids and the process names	
 	mv $join_file temp_join_file
 	join -a 2   temp_join_file srmd_sec_$latest_1_sec > $join_file 2> /dev/null
 	WORD=`awk '{print $1}' $join_file`
 	gen_pid_file "$WORD"
 	awk -v n_cores=$ncores range=$1' {
 		for(i=0;i<n_cores;++i)
 			core_sum[i] = 0;
 		for(i=2;i<range+2;++i) {
 			split($i,core," ");
 			for(j=0;j<n_cores;++j)
 				core_sum[j]+=core[2+j];
 		}
 		for(i=0;i<n_cores;++i)
 			printf ("%.2f\t", 100*(core_sum[i]/range));
 		printf("\n");
 	}' $join_file | paste pid_file - > core_info
 	awk -v n_cores=$ncores ' 
 	BEGIN {
 		printf("%-6s %-16s ", "PID","Process");
 		for(i=0;i<n_cores;++i)
 			printf("C%d\t\t", i);
 		printf("\n\n");
 	}
 	{
 		printf ("%-6d %-16s ", $1, $2); 
 		for (i=3;i<n_cores+3;++i) {
 			printf("%-.2f%%\t\t",$i);
 		}
 		printf("\n");
 	}' core_info
 	rm -f core_info $join_file $op_file
	core_id=$1	
#	# collect data for different time intervals
#	awk -F'[ #]' -v core_num=$core_id '{printf("%s\t%.4f\n",$1,$(1+core_num))}' srmd_minute_1 > 1min_info_core_$core_id
#	awk -F'[ #]' -v core_num=$core_id '{printf("%s\t%.4f\n",$1,$(1+core_num))}' srmd_minute_5 > 5min_info_core_$core_id
#	awk -F'[ #]' -v core_num=$core_id '{printf("%s\t%.4f\n",$1,$(1+core_num))}' srmd_minute_10 > 10min_info_core_$core_id
#	
#	awk -F'[ #]' -v core_num=$core_id '{printf("%s\t%.4f\n",$1,$(1+core_num))}' srmd_hour_1 > 1hour_info_core_$core_id
#	awk -F'[ #]' -v core_num=$core_id '{printf("%s\t%.4f\n",$1,$(1+core_num))}' srmd_hour_5 > 5hour_info_core_$core_id
#	awk -F'[ #]' -v core_num=$core_id '{printf("%s\t%.4f\n",$1,$(1+core_num))}' srmd_hour_10 > 10hour_info_core_$core_id
#	
#	awk -F'[ #]' -v core_num=$core_id '{printf("%s\t%.4f\n",$1,$(1+core_num))}' srmd_day_1 > 1day_info_core_$core_id
#	awk -F'[ #]' -v core_num=$core_id '{printf("%s\t%.4f\n",$1,$(1+core_num))}' srmd_day_5 > 5day_info_core_$core_id
#	
#	#join and display the data
#	join  1min_info_core_$core_id 5min_info_core_$core_id \
#	| join  - 10min_info_core_$core_id | join  - 1hour_info_core_$core_id  \
#	| join  - 5hour_info_core_$core_id | join  - 10hour_info_core_$core_id \
#	| join  - 1day_info_core_$core_id | join  -  5day_info_core_$core_id \
#	| awk -F'[ ^]' '{printf("%-6d %-16s %-2.2f %-2.2f %-2.2f %-2.2f %-2.2f %-2.2f %-2.2f %-2.2f", $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)}' 
}

make_core_input() 
{
	parm=$1
	if [ $parm = "min" ] || [ $parm = "minute" ] || [ $parm = "minutes" ] || [ $parm = "m" ]
	then
		core_input="minute" 
	elif [ $parm = "hr" ] || [ $parm = "hour" ] || [ $parm = "hours" ] || [ $parm = "h" ]
	then
		core_input="hour"
	elif [ $parm = "d" ] || [ $parm = "day" ] || [ $parm = "days" ] || [ $parm = "d" ]
	then
		core_input="day"
	elif [ $parm = "mon" ] || [ $parm = "month" ] || [ $parm = "months" ] 
	then
		core_input="month"
	fi

}

SRMD_DIR=/var/srmd_data/
if [ "$#" -eq  "0" ]; then
	show_default
fi

while [ "$#" -gt "0" ]
do
	case $1 in
	-e)
		#Enable the srmd
		if [ -e /tmp/srmd_enabled ]; then
			echo "SRMD already enabled"
			exit 1
		fi
		/fabos/bin/srmd&
		if [ "$?" -eq "0" ]; then
			echo "SRMD enabled"
			touch /tmp/srmd_enabled
		else
			echo "Cannot enable srmd"
		fi	
	;;
	
	-k)
		if [ -e /tmp/srmd_enabled ]; then 
			srmd_pid=`ps ax | grep srmd | grep -v grep| awk '{print $1}'`
			kill -9 $srmd_pid
			rm  /tmp/srmd_enabled
		else
			echo "SRMD not enabled"
		fi	
	;;

	-F)
		shift 
		if [ "$#" -eq "0" ];then
			echo "Archive directory name required"
			exit 1
		fi
		#Check if file exists or not
		ARC_DIR="$1"
		if [ ! -d "$ARC_DIR" ] ; then
			ARC_DIR=$PWD/$1
		fi	
		if [ ! -d "$ARC_DIR" ]; then 
			echo "Archive does not exist"
			exit 1
		fi
		#Check for a valid archive file
		archive_dir=0
		for i in $ARC_DIR/*
		do
			if [ "$i" = "$ARC_DIR/archived_srmd" ] 
			then
				archive_dir=1
     			fi
		done
		if [ "$archive_dir" = "1" ]
		then
			SRMD_DIR=$ARC_DIR
		else	
			echo "Invalid Archive"
			exit 1
		fi
	;;	

	-f)
		shift
		if [ "$#" -eq "0" ];then
			echo "Archive name required"
			exit 1
		fi
		#Check if file exists or not
		ARC_FILE="$1"
		if [ ! -f "$ARC_PATH" ] ; then
			ARC_PATH=$PWD/$1
		fi	
		if [ ! -f "$ARC_FILE" ]; then 
			echo "Archive does not exist"
			exit 1
		fi
		rm -rf /tmp/var/srmd_data/
		tar xzf $ARC_FILE -C /tmp
		#Check for a valid archive file
		archive_file=0
		for i in /tmp/var/srmd_data/*
		do
			if [ "$i" = "/tmp/var/srmd_data/archived_srmd" ] 
			then
				archive_file=1
     			fi
		done
		if [ "$archive_file" = "1" ]
		then
			SRMD_DIR=/tmp/var/srmd_data/
		else	
			echo "Invalid Archive"
			exit 1
		fi
	;;
	-d)
		show_days
	;;
	-h)
		show_hours
	;;
    -u)
        show_cpu_utilz $2
        shift 1
	;;    
	-core)
		make_core_input $3 
		show_core_info $2 $core_input 
		shift 2
	;;	
	*)
		echo "Usage: show-cpu-usage -[dh:core [duration]] -f <Archive file>/-F <Archive directory>"
		echo " -h: Hours"
		echo " -d: Days"
		#echo " -m: Months"
		echo " -e: Enable SRMD"
		echo " -k: Kill SRMD"
		echo " -core <duration>: Per core information. Duration can range from 1 minute to 3 days"
	;;
	esac
	shift
done	
rm -rf /tmp/var/srmd_data/
