#!/bin/bash

if [ `id -u` -ne 0 ] ; then echo "Please run as root" ; exit 1 ; fi

tput setaf 5 ;
echo "============================================="
echo "Cloud Assessment Data Capture - Pugmarks Inc."
echo "============================================="
tput sgr0;

command -v curl >/dev/null 2>&1 || {
        tput setaf 1 ;
        echo  "This script requires curl. Please install curl and run this script again. Aborting.";
        tput sgr0;
        exit 1;
}

if [ $# -ne 4 ]; then
        echo ; echo "Usage: \n$0 <email> <secret> <sample-time> <test-period>\n"
        echo "Where:"
        echo -e "email \t\t  User email"
        echo -e "secret \t\t  Server secret"
        echo -e "sample-time \t  Sampling time interval in minutes"
        echo -e "test-period \t  Duration to test in hours"; echo
        exit 1
fi

email=$1
secret=$2
sample_t=$3
period=$4

no_runs=`expr $period \* 60 / $sample_t`
sleep_t=`expr $sample_t \* 60`
#sleep_t=5
tmpfile=`mktemp`
samplefile=`mktemp`
#echo $tmpfile

#if [ ! -w "/dev/mem" ]; then echo "Could not write to temp file" ; exit 1 ; fi

echo "Preparing environment...."
ARCH=$(uname -m | sed 's/x86_//;s/i[3-6]86/32/')
if [ -f /usr/bin/lsb_release ]; then
        OS=$(lsb_release -d|sed 's/Description:\t//')
        apt-get -y install dmidecode >/dev/null 2>&1
elif [ -f /etc/redhat-release ]; then
        OS=$(cat /etc/redhat-release)
        yum -y install dmidecode >/dev/null 2>&1
else
        OS="$(uname -s) $(uname -r)"
fi
echo "Done."

sys_uuid=`dmidecode -s system-uuid`
out_file=$sys_uuid-`date +%F@%R:%S`

if [ -z "$sys_uuid" ]; then
        tput setaf 1 ;
        echo "Could not read the UUID for this server. Data was not submitted."
        tput sgr0;
        exit 1
fi

echo "{\"sysinfo\":" >> $tmpfile
echo "Capturing one-time system info data...."
echo "{" >> $tmpfile
echo "\"info\":\"Cloud Assessment Data Capture - Pugmarks Inc.\"," >> $tmpfile

echo "\"time\":\"`date`\"," >> $tmpfile
echo "\"hostname\":\"`hostname`\"," >> $tmpfile
echo "\"manufacturer\":\"`dmidecode -s system-manufacturer`\"," >> $tmpfile
echo "\"product\":\"`dmidecode -s system-product-name`\"," >> $tmpfile
echo "\"serial\":\"`dmidecode -s system-serial-number`\"," >> $tmpfile
echo "\"uuid\":\"$sys_uuid\"," >> $tmpfile
echo "\"user\":\"`whoami`\"," >> $tmpfile
echo "\"os\":\"$OS\"," >> $tmpfile
echo "\"os_arch\":\"$ARCH\"," >> $tmpfile
echo "\"processor\":\"`cat /proc/cpuinfo|grep name|head -1|cut -f2 -d:`\"," >> $tmpfile
echo "\"processor_count\":\"`dmidecode -s processor-version|wc -l`\"," >> $tmpfile
echo "\"core-thread_count\":\"`cat /proc/cpuinfo|grep processor|wc -l`\"," >> $tmpfile
echo "\"total_memory\":\"`cat /proc/meminfo|grep MemTotal|awk '{print $2 $3}'`\"," >> $tmpfile
echo "\"free_memory\":\"`cat /proc/meminfo|grep MemFree|awk '{print $2 $3}'`\"," >> $tmpfile
echo "\"total_swap\":\"`cat /proc/meminfo|grep SwapTotal|awk '{print $2 $3}'`\"," >> $tmpfile
echo "\"free_swap\":\"`cat /proc/meminfo|grep SwapFree|awk '{print $2 $3}'`\"," >> $tmpfile
echo "\"disk\":\"`lsblk -d -o NAME,TYPE|grep disk|wc -l`\"," >> $tmpfile
echo "\"disk_size\":\"`df -h --total --block-size=K|grep total|awk '{print $2}'`\"," >> $tmpfile
echo "\"disk_used\":\"`df -h --total --block-size=K|grep total|awk '{print $3}'`\"," >> $tmpfile

echo "\"processors\":[" >> $tmpfile
count=0
cat /proc/cpuinfo|grep name |{
        while read t; do
        count=$((count+1))
        done

        for i in $(seq $count)
        do
        p=$(printf "%sp" "$i")
        echo "{" >> $tmpfile ;
        cat /proc/cpuinfo|grep name | sed -n $p |
        while read a b c cpu; do
                echo "\"caption\":\"$cpu\"," >> $tmpfile
        done
        cat /proc/cpuinfo|grep family | sed -n $p |
        while read a b c family; do
                echo "\"family\":\"$family\"," >> $tmpfile
        done
        cat /proc/cpuinfo|grep cores | sed -n $p |
        while read a b c cores; do
                echo "\"cores\":\"$cores\"," >> $tmpfile
        done
        lscpu|grep Architecture|
        while read a arch; do
                echo "\"version\":\"$arch\"" >> $tmpfile
        done
        if [ $i == $count ]; then
                echo "}" >> $tmpfile
        else
                echo "}," >> $tmpfile
        fi
        done
}
echo "]," >> $tmpfile

echo "\"disks\":[" >> $tmpfile
count=`df -h --block-size=MB -T|grep -v blocks |grep -v tmpfs|wc -l`
i=0
df -h --block-size=MB -T|grep -v blocks |grep -v tmpfs |
while read name ptype total used free usage mount; do
        echo "{" >> $tmpfile ;
        echo "\"name\":\"$name\"," >> $tmpfile
        echo "\"freesize\":\"$free\"," >> $tmpfile
        echo "\"totalsize\":\"$total\"," >> $tmpfile
        echo "\"usedsize\":\"$used\"" >> $tmpfile
        i=`expr $i + 1`
        if [ $i == $count ]; then
                echo "}" >> $tmpfile
        else
                echo "}," >> $tmpfile
        fi
done
echo "]," >> $tmpfile

echo "\"ips\":[" >> $tmpfile
count=`ip a|grep 'inet '|grep -v 127.0 | wc -l`
i=0
ip a|grep 'inet '|grep -v 127.0 |
while read ntype ip scope link; do
        i=`expr $i + 1`
        if [ $i == $count ]; then
                echo "\"$ip\"" >> $tmpfile
        else
                echo "\"$ip\"," >> $tmpfile
        fi
done
echo "]," >> $tmpfile

echo "\"processes\":[" >> $tmpfile
count=`ps aux | sort -nr -k 3 |grep -v TTY | head -10 | wc -l`
i=0
ps aux | sort -nr -k 3 |grep -v TTY | head -10  |
while read user pid cpu mem vsz rss tty stat start t cmnd; do
        echo "{" >> $tmpfile ;
        echo "\"user\":\"$user\"," >> $tmpfile
        echo "\"pid\":\"$pid\"," >> $tmpfile
        echo "\"cpu\":\"$cpu\"," >> $tmpfile
        echo "\"mem\":\"$mem\"," >> $tmpfile
        echo "\"vsz\":\"$vsz\"," >> $tmpfile
        echo "\"rss\":\"$rss\"," >> $tmpfile
        echo "\"tty\":\"$tty\"," >> $tmpfile
        echo "\"stat\":\"$stat\"," >> $tmpfile
        echo "\"start\":\"$start\"," >> $tmpfile
        echo "\"t\":\"$t\"," >> $tmpfile
        cmnd=`echo $cmnd|tr '"' ':'|tr ',' ':'`
        echo "\"name\":\"$cmnd\"" >> $tmpfile
        i=`expr $i + 1`
        if [ $i == $count ]; then
                echo "}" >> $tmpfile
        else
                echo "}," >> $tmpfile
        fi
done
echo "]," >> $tmpfile

echo "\"services\":[" >> $tmpfile
if grep '^NAME="Ubuntu"$' /etc/os-release > /dev/null 2>&1; then
        service --status-all 2>&1 | grep '\[ + ]' | awk '{print $4}' |
        while read name options; do
        echo "{" >> $tmpfile ;
        echo "\"name\":\"$name\"," >> $tmpfile
                echo "\"status\":\"running\"" >> $tmpfile
        echo "}," >> $tmpfile
        done
else
        chkconfig --list | grep '3:on' |
        while read name options; do
        echo "{" >> $tmpfile ;
        echo "\"name\":\"$name\"," >> $tmpfile
                echo "\"status\":\"running\"" >> $tmpfile
        echo "}," >> $tmpfile
        done
fi
sed -i '$s/^\}\,$/}/g' $tmpfile

echo "]," >> $tmpfile
echo "\"ports\":[" >> $tmpfile ;
netstat -plan | grep LISTEN | grep -v ^unix |
while read protocol mss win loc fore status bnd; do
        echo "{" >> $tmpfile ;
        echo "\"protocol\":\"$protocol\"," >> $tmpfile
        echo "\"local_address\":\"$loc\"," >> $tmpfile
        echo "\"foreign_address\":\"$fore\"," >> $tmpfile
        echo "\"status\":\"$status\"" >> $tmpfile
        echo "}," >> $tmpfile
done
sed -i '$s/^\}\,$/}/g' $tmpfile
echo "]" >> $tmpfile

echo "}" >> $tmpfile

echo "Done."


tput setaf 6 ;
echo "Script will continue to run for the next $period hours taking samples each $sample_t minutes"
tput sgr0;

echo ",\"performance\":" >> $tmpfile

echo "[" >> $tmpfile
for i in `seq 1 $no_runs`; do

        tmpsample=`mktemp`
        if grep '^NAME="Ubuntu"$' /etc/os-release > /dev/null 2>&1; then
        top  -n 1 -b |head -4 > $tmpsample; df --total -m|tail -1 >> $tmpsample
        idle=`grep ^%Cpu $tmpsample|awk '{print $8}'`
        else
        top  -n 1 -b |head -4 > $tmpsample; df --total -m|tail -1 >> $tmpsample
        idle=`grep ^Cpu $tmpsample|cut -f4 -d%|awk '{print $2}'`
        fi
        if [ `echo $idle|cut -f2 -d.` -ge 5 ]; then export cpu=`echo $idle|cut -f1 -d.`; cpu=`expr 100 - $cpu - 1`; else export cpu=`echo $idle|cut -f1 -d.`; cpu=`expr 100 - $cpu`; fi
        load_avg=`grep ^top $tmpsample|cut -f5 -d,|awk '{print $1}'`
        io_wait=`grep ^Cpu $tmpsample|cut -f5 -d%|awk '{print $2}'`
        memused=`grep ^Mem $tmpsample|awk '{print $4}'`
        membuffered=`grep ^Mem $tmpsample|awk '{print $8}'`
        memtotal=`grep ^Mem $tmpsample|awk '{print $2}'`
        diskused=`grep ^total $tmpsample|awk '{print $3}'`
        disktotal=`grep ^total $tmpsample|awk '{print $2}'`

        echo "{" >> $tmpfile
        echo "\"time\":\"`date`\"," >> $tmpfile
        echo "\"cpu\":\"$cpu\"," >> $tmpfile
        echo "\"load_avg\":\"$load_avg\"," >> $tmpfile
        echo "\"io_wait\":\"$io_wait\"," >> $tmpfile
        echo "\"memused\":\"$memused\"," >> $tmpfile
        echo "\"membuffered\":\"$membuffered\"," >> $tmpfile
        echo "\"memtotal\":\"$memtotal\"," >> $tmpfile
        echo "\"diskused\":\"$diskused\"," >> $tmpfile
        echo "\"disktotal\":\"$disktotal\"" >> $tmpfile
        echo "}," >> $tmpfile

        tput setaf 2 ;
        echo "Result:"
        echo "CPU \t\t$cpu"
        echo "Load Avarage \t$load_avg"
        echo "Mem Total \t$memtotal"
        echo "Mem Used \t$memused"
        echo "Mem Buffered \t$membuffered"
        echo "Disk Total \t$disktotal"
        echo "Disk Used \t$diskused"
        tput sgr0;

        echo "Sleeping $sleep_t seconds..."

        rm $tmpsample

        sleep $sleep_t

done

sed -i '$s/^\}\,$/}/g' $tmpfile


echo "]" >> $tmpfile
echo "}" >> $tmpfile
echo "Done."

tput setaf 6 ;
echo -e "\n\nSubmitting data to server..."

json=$(cat $tmpfile)
curl -X POST -H "Content-Type: application/json" \-d @$tmpfile \--url "http://207.191.234.131/api/submit?email=$email&secret=$secret"

tput setaf 2 ;
echo -e "\nData submission complete."
tput sgr0;

tput setaf 5 ;
echo -e "\n\n============================================="
echo "Submitted data saved locally at : $tmpfile"
echo -e "=============================================\n\n"
tput sgr0;
