#!/bin/bash
set -u

DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
MYSQLITE3="$DIR"/sqlite3

# check number of arguments
if [ $# -ne 1 ]; then
    echo " usage: ${BASH_SOURCE[0]} [SQLite DB file exported from NSys QDREP file]"
    exit 1
fi

# check if file exists
if [ ! -f "$1" ]
then
    echo "$1 file not found. Exiting"
    exit 1
fi

# check if file opened is DB; if not, exit
# The sqlite3 file format is defined at https://www.sqlite.org/draft/fileformat.html
HEADER=$(head -c 16 "$1" | tr '\0' '\n')
if [ "$HEADER" != "SQLite format 3" ]
then
    echo "$1 is not an SQlite DB file. Exiting."
    exit 1
fi

# check if DB contains osrt API data; if not, exit
COUNT=$("$MYSQLITE3" "$1" "SELECT COUNT(*) FROM OSRT_API");
if [ $COUNT -eq 0 ]
then
    echo "OS Runtime trace data was not collected."
    exit 0
fi

# check if osrtAPIStats table exists
if [ "$("$MYSQLITE3" "$1" "SELECT name FROM sqlite_master WHERE type='table' AND name='osrtAPIStats';")" != "osrtAPIStats" ]
then
    printf "\nGenerating Operating System Runtime API Statistics...\n"

    "$MYSQLITE3" "$1" <<GenerateSummary
    PRAGMA SYNCHRONOUS=OFF;
    CREATE TABLE osrtAPIStats (nameId INTEGER, num INTEGER, min INTEGER, max INTEGER, avg INTEGER, total INTEGER);
    INSERT INTO osrtAPIStats SELECT nameId, count(nameId), min(end-start), max(end-start), avg(end-start), sum(end-start)
        FROM OSRT_API WHERE eventClass = 27 GROUP BY nameId;
GenerateSummary
fi

printf "Operating System Runtime API Statistics (nanoseconds)\n\n"
TOTALTIME=$("$MYSQLITE3" "$1" "SELECT sum(total) FROM osrtAPIStats");
echo -e ".width -7 -14 -10 -14 -14 -14 80 \n SELECT
    round((total*100.0)/$TOTALTIME,1) as 'Time(%)', total as 'Total Time',
    num as Calls, round(avg,1) as 'Average', min as 'Minimum',
    max as 'Maximum', value as Name
    FROM osrtAPIStats INNER JOIN StringIds ON StringIds.id = osrtAPIStats.nameId
    ORDER BY total DESC;" | "$MYSQLITE3" -column -header "$1"

printf "\n\n"
