#!/bin/bash

export GNUPLOT_DEFAULT_GDFONT=inconsolata

job=$(realpath "$1")
confuga=$(realpath "$2")

data=$(mktemp)

echo $0

T=$(mktemp)
sqlite3 -separator $'\t' > "$T" <<EOF
ATTACH 'file://${job}?immutable=1' as Job;
ATTACH 'file://${confuga}?immutable=1' as Confuga;

SELECT COUNT(*) FROM Confuga.StorageNode;
EOF
N=$(cat "$T")
rm "$T"

sqlite3 -separator $'\t' > "$data"  <<EOF
ATTACH 'file://${job}?immutable=1' as Job;
ATTACH 'file://${confuga}?immutable=1' as Confuga;

WITH
	TransferredBytes AS (
		SELECT StorageNode.id, SUM(File.size) AS sent
			FROM
				Confuga.StorageNode
				JOIN Confuga.TransferJob ON StorageNode.id = TransferJob.fsid
				JOIN Confuga.File ON TransferJob.fid = File.id
			WHERE TransferJob.state = 'COMPLETED'
			GROUP BY StorageNode.id
	),
	ReceivedBytes AS (
		SELECT StorageNode.id, SUM(File.size) AS received
			FROM
				Confuga.StorageNode
				JOIN Confuga.TransferJob ON StorageNode.id = TransferJob.tsid
				JOIN Confuga.File ON TransferJob.fid = File.id
			WHERE TransferJob.state = 'COMPLETED'
			GROUP BY StorageNode.id
	),
	ProcessedBytes AS (
		SELECT StorageNode.id, SUM(File.size) AS processed
			FROM
				Confuga.StorageNode
				JOIN Job.ConfugaJob ON StorageNode.id = ConfugaJob.sid
				JOIN Job.ConfugaInputFile ON ConfugaJob.id = ConfugaInputFile.jid
				JOIN Confuga.File ON ConfugaInputFile.fid = File.id
			WHERE ConfugaJob.state = 'BOUND_OUTPUTS'
			GROUP BY StorageNode.id
	)
SELECT StorageNode.id, PRINTF('%d', TransferredBytes.sent), PRINTF('%d', ReceivedBytes.received), PRINTF('%d', ProcessedBytes.processed)
	FROM
		Confuga.StorageNode
		LEFT OUTER JOIN TransferredBytes ON StorageNode.id = TransferredBytes.id
		LEFT OUTER JOIN ReceivedBytes ON StorageNode.id = ReceivedBytes.id
		LEFT OUTER JOIN ProcessedBytes ON StorageNode.id = ProcessedBytes.id
	ORDER BY StorageNode.id;
EOF
cat "$data"

gnuplot <<EOF
set terminal postscript eps mono
set output 'sn-activity.eps'

set auto fix
set key outside
set logscale y
set offset 1, 1
set style data histograms
set style histogram clustered
set title "Data Transferred, Received, and Processed"
set xlabel "Storage Node"
set xtics 1, 1, ${N}
set xtics rotate by -90 offset 0,0
set ylabel "Bytes"
set yrange [1:]

set size ratio 0.5

plot "${data}" using 2:xticlabels(1) title "Transferred" fill pattern 0, "" using 3:xticlabels(1) title "Received" fill pattern 2, "" using 4:xticlabels(1) title "Processed" fill pattern 3
EOF

# vim: set noexpandtab tabstop=4:
