#!/usr/bin/perl
#
use strict;
use warnings;
use RRDs;
use Data::Dumper;
use Template;

my $file = $ARGV[0] or die("Usage: $0 csv\n");

my $rrdpath = "/var/www/localhost/rrd";
my $cryptoMap = {
	"AAVE" => "AAVE",
	"ALGO" => "Algorand",
	"BTC"  => "Bitcoin",
	"CVC"  => "Civic",
	"DNT"  => "district0x",
	"EGLD" => "Elrond eGold",
	"ETH"  => "Etherium",
	"LRC"  => "Loopring",
	"REN"  => "REN",
	"SNX"  => "Synthetix",
	"XLM"  => "Stellar Lumen",
	"XTZ"  => "Tezos"
};
my $v;
my $alarmThresh = 15;

sub getCurrentPrice {
	my ($symbol) = @_;
	my ($start,$step,$name,$data) = RRDs::fetch("${rrdpath}/crypto-${symbol}.rrd","LAST","--start","-10m");
	return($data->[0]->[0]);
}

sub getLast4hAverage {
	my ($symbol) = @_;
	my ($start,$step,$name,$data) = RRDs::fetch("${rrdpath}/crypto-${symbol}.rrd","AVERAGE","--start","-4h","-r",'4h');
	return($data->[0]->[0]);
}

open(CSV,"<$file") or die("open($file): $!\n");

while (<CSV>) {
	chomp($_);
	my ($date,$currency,$coin,$price,$fee,$buyrate,$sellthres) = split /;/;
	my $curPrice   = sprintf("%.4f",&getCurrentPrice($currency));
	my $avg4hPrice = sprintf("%.4f",&getLast4hAverage($currency));
	if($avg4hPrice > ((1 + int($alarmThresh)/100) * $curPrice)) {
		$v->{$currency} = "current price dropped by more than ${alarmThresh}% from $avg4hPrice Euro/$currency to $curPrice Euro/$currency within 4h";
	}
}
close(CSV);

foreach my $c (sort keys %{$v}) {
	print "<b>$cryptoMap->{$c}</b>: $v->{$c}<br/>\n";
}