#!/bin/bash
#

# Activate Bash Strict Mode
set -euo pipefail

main() {
    {
        local maxLen=0
        for url in ${@:2}; do
            local size=${#url}
            if [[ $size -gt $maxLen ]]
                then maxLen=$size
            fi
        done

        printf "%-${maxLen}s   %+4s %+5s %+9s %+9s %+9s %+9s\n" "URL" "Runs" "StDev" "Min (ms)" "Avg (ms)" "Max (ms)" "1st (ms)"
        for url in ${@:2}; do
            get_statistics $url $1 $maxLen
        done
    } #| column -s $'\t' -t
}

get_statistics() {
    # Initialice the variables
    local first=-1
    local min=1000000000
    local max=0
    local dur=0
    local durQ=0
    local spin=0
    local activeSpinner=0
    local spiner=('-' '\' '|' '/')

    printf "%-${maxLen}s   " $1
    if [[ $activeSpinner -ne 0 ]]
        then printf " "
    fi
    #echo -ne "$1\t "

    # repeat for the defined counts the url calling
    for i in $(seq 1 $2); do
        if [[ $activeSpinner -ne 0 ]]
            then echo -ne "\b${spiner[$spin]}"
        fi
        spin=$(( (spin+1) % 4 ))
        local gp=$(($(get_posts $1)/1000000)) # from ns to ms
        if [[ $first -lt 0 ]]
            then first=$gp
        fi
        if [[ $gp -gt $max ]]
            then max=$gp
        fi
        if [[ $gp -lt $min ]]
            then min=$gp
        fi
        dur=$(( $dur + $gp ))
        durQ=$(( $durQ + $(($gp * $gp)) ))
    done

    local avg=$(($dur/$2))
    local avgPow=$(($avg * $avg))
    local stdev=$( echo "sqrt(($durQ / $2) - $avgPow)" | bc )

    # output the statistic values
    if [[ $activeSpinner -ne 0 ]]
        then echo -ne "\b"
    fi
    printf "%+4s %+5s %+9s %+9s %+9s %+9s\n" $2 $stdev $min $avg $max $first
    #echo -e "\b$2\t$stdev\t$min\t$avg\t$max\t$first"
}

get_posts() {
    # Call the url with measure time
    local start=$(date +%s%N)
    curl --silent --show-error $1 > /dev/null
    local stop=$(date +%s%N)
    local dur=$(($stop-$start))
    echo $dur
}

print_process() {
    ps -C java --no-headers --format "pid %cpu %mem rss pss cmd" |\
        awk 'BEGIN { printf "%6s %5s %4s %13s %13s %-50s\n", "pid", "%cpu", "%mem", "rss Mb", "pss Mb", "cmd"} 
        {hr=$4/1024; hp=$5/1024; printf("%6i %5.1f %4.1f %13.2f %13.2f %s\n", $1, $2, $3,hr, hp, $6) }'
}

print_docker_process() {
    sudo docker stats --no-stream
}

# the main domain
#hostname="https://briefedition.wedekind.h-da.de"
hostname="http://localhost:8080/WedekindJSF-1.0.0"

# the Array of the Urls
url_arr=(
    "$hostname/index.xhtml"
    "$hostname/view/document/list.xhtml"
    #"$hostname/view/document/listsearch.xhtml"
    #"$hostname/view/correspondent/list.xhtml"
    #"$hostname/view/person/list.xhtml"
)

#print_process
print_docker_process
echo ""
 
# Execute all the URLs for 10 rounds
main 10 ${url_arr[@]}

echo ""
##print_process
print_docker_process
