#!/bin/bash
# usage:
## both quoted and unquoted commands work for oneshot mode~
###     measure_performance my_command -with -args
###     measure_performance "my_command -with -args"
## if $1 is a file, it will read as text and test the commands, one per line
###     measure_performance path/to/file.txt
####    file.txt
####        rm -rf ~/Downloads
####        sleep 10
####        wget https://example.com/file.zip
####        unzip file.zip

# todo: calculate human readable sizes for mem, r and w

# glooboos
poll_seconds=2
logfile=/tmp/sillylog.tmp # can beee a temp fiel
input="$@" # da command as a string or as args
duration_microseconds=0
duration_seconds=0
csv_file="${input%.*}.csv"
test_cmd=""
start_seconds=$(date +%s)

# throw a fit if no args supplied
if [ -z "$1" ]; then
    echo 'USAGE: measure_performance "string_command-with -args"'
    exit 1
fi

# maek sure da log fileee DIESASDRGVWERT
if [ -f "$logfile" ]; then
    rm  -f "$logfile"
fi

# maek sure da log fileee DIESASDRGVWERT
if [ -f "$csv_file" ]; then
    rm  -f "$csv_file"
fi

measure_performance () {
    if [ -f "$logfile" ]; then
        rm -f "$logfile"
    fi

    # use microseconds for timing for ONE MILLION DOLLARS more times resolution
    start_unixmicroseconds=$(date +"%s%6N") # get start microseconds fast as possible before run

    # run the command with pidstart (-e)
    eval "pidstat -h -T ALL -H -d -r -u $poll_seconds -e bash -c \"($test_cmd >/dev/null 2>&1)\" >> \"$logfile\""
    ret=$? # get da return code
    
    # calculate durations
    end_unixmicroseconds=$(date +"%s%6N") # get dis fast for accuracy
    duration_microseconds=$(($end_unixmicroseconds - $start_unixmicroseconds))
    duration_seconds=$(($duration_microseconds / 1000000)) # seconds = microseconds / 1,000,000

    if [ ! -f "$input" ]; then
        echo "testing your gay littel command: $test_cmd"
        # parse and show infos
        cat "$logfile" | sed '/^#\|^$\|^Linux/d' | tr -s ' ' ',' | awk -F, '{ cpup += $8; memk += $13; memp += $14; rkbs += $15; wkbs += $15 } END { print "\nCPU:",cpup/NR,"\nMemory Usage (KiB):",memk/NR,"\nMemory Usage %:",memp/NR,"\nKiB Read Per Second:",rkbs/NR,"\nKiB Written Per Second:",wkbs/NR }'
        
        # nao add da rest
        echo -e "Duration Seconds: $duration_seconds\nDuration Microseconds: $duration_microseconds\nReturn Code: $ret"
    else
        elapsed_seconds=$((`date +%s` - $start_seconds))
        # parse and appand dem 2 da csv
        cat "$logfile" | sed -n '/^[0-9]/p' | tr -s ' ' ',' | awk -F, "{cpup+=\$8;memk+=\$13;memp=\$14;rkbs+=\$15;wkbs+=\$15}{print \"$position\",\",\",cpup/NR,\",\",memk/NR\",\",memp/NR,rkbs/NR,wkbs/NR,\"$duration_microseconds\",\",$elapsed_seconds\",\",\",\"$friendly_test_cmd\",\",\",\"$ret\"}" | tee -a "$csv_file"
    fi
}

# main
## awk testarrrr
## cat /tmp/sillylog.tmp | sed '/^#\|^$\|^Linux/d' | tr -s ' ' ',' | awk -F, '{print "Time:",$1,"UID:",$2,"PID:",$3,"%usr:",$4,"%system:",$5,"%guest:",$6,"%wait:",$7,"%CPU:",$8,"CPU:",$9,"minflt/s:",$10,"majflt/s:",$11,"VSZ:",$12,"RSS:",$13,"%MEM:",$14,"kB_rd/s:",$15,"kB_wr/s:",$16,"kB_ccwr/s:",$17,"iodelay:",$18,"Command:",$19}'
## if oneshot mode
if [ ! -f "$input" ]; then
    test_cmd="$(echo \"$input\" | sed 's/\ /_/g')"
    echo $test_cmd
    measure_performance
## if batch mode
else
    # settans
    len=$(wc -l "$input" | awk '{print $1}') # num of lines in da fiel
    count=1
    
    # add da csv headers to the results fiel
    echo "0Position,CPU %,Memory (KiB),Memory %,KiB Read/Second,KiB Written/Second,Duration Microseconds,Command,Return Code" > "$csv_file"

    cat "$input" | \
        while read line; do
            test_cmd="$line"
            friendly_test_cmd=$(echo "$line" | tr -s ' ' '_')
            position="$count/$len"
            measure_performance
            count=$(($count + 1))
        done
fi