#!/bin/bash

set -e

# Generate statistics from uwsgi logfiles and database logs

mkdir -p data

grep HTTP "$@" | cut -d " " -f 12-17,19,25,28 | while read weekday month day time year request_uri duration status_code; do
    weekday="${weekday/\[/}"
    year="${year/\]/}"
    parsed_date="$(date -d "$weekday $month $day $time " +%s)"

    status_code="${status_code/\)/}"

    request_uri="${request_uri//\//_}"

    echo $parsed_date $duration $status_code >> data/$request_uri
done

psql -h prado.internal.softwareheritage.org -U olasd softwareheritage-log <<EOF
 \a
 \t
 \o data/successes
 select ts, trim(both 's:' from split_part(message, ' ', 8))::float from log where message ~~ '%succeeded%' order by ts;
EOF

{
    count=0
    for file in data/_*; do
	echo set term qt $count
	echo set xdata time
	echo set timefmt '"%s"'
	echo plot "'$file'" using 1:2, "'$file'" using 1:3 axes x1y2
	count=$((count + 1))
    done
    echo set term qt $count
    echo 'set datafile separator "|"'
    echo set timefmt '"%Y-%m-%d %H:%M:%S+%z"'
    echo plot "'data/successes'" using 1:2
    echo pause 100000
} | gnuplot -p
