#! /usr/bin/perl
use strict;
use warnings;
no warnings qw(once);
use CGI;
use JSON::XS;
use Digest::SHA qw(hmac_sha256_hex);
use LWP::UserAgent;
use DBI;

require '../include/config.pm';

sub mark {
	print STDERR "Marking that a sync is needed.\n";
	open my $fh, ">", "/srv/skvidar-slack.sesse.net/marker";
	close $fh;
}

my $dbh = DBI->connect("dbi:Pg:dbname=$config::dbname;host=127.0.0.1", $config::dbuser, $config::dbpass, {RaiseError => 1})
	or die "Could not connect to Postgres: " . DBI->errstr;

my $cgi = CGI->new;
my $post = $cgi->param('POSTDATA');
my $ts = $cgi->http('X-Slack-Request-Timestamp');
my $sig = $cgi->http('X-Slack-Signature');

my $digest = Digest::SHA::hmac_sha256_hex("v0:$ts:$post", $config::signing_secret);
die "Failed signature" unless ($sig eq "v0=$digest");

print STDERR "JSON: $post\n";

my $json = JSON::XS::decode_json($post);
if (exists($json->{'challenge'})) {
	print CGI->header(-type=>'text/plain');
	print $json->{'challenge'}, "\n";
	exit;
}

if (exists($json->{'event'}) && exists($json->{'event'}{'type'})) {
	my $type = $json->{'event'}{'type'};
	my $reaction = $json->{'event'}{'reaction'};
	my $channel = $json->{'event'}{'item'}{'channel'};
	my $ts = $json->{'event'}{'item'}{'ts'};
	my $event_ts = $json->{'event'}{'event_ts'};
	my $user = $json->{'event'}{'user'};

	if (!defined($channel) || !defined($ts)) {
		print STDERR "Not reacting to a message; ignoring.\n";
		print CGI->header(-type=>'text/plain');
		print "OK\n";
		exit;
	}

	if ($type eq 'reaction_added') {
		$dbh->do('INSERT INTO reaction_log (userid, channel, ts, reaction, event_type, event_ts) VALUES (?,?,?,?,?,?)', undef,
			$user, $channel, $ts, $reaction, $type, $event_ts);
		mark();
	} elsif ($type eq 'reaction_removed') {
		$dbh->do('INSERT INTO reaction_log (userid, channel, ts, reaction, event_type, event_ts) VALUES (?,?,?,?,?,?)', undef,
			$user, $channel, $ts, $reaction, $type, $event_ts);
		mark();
	} else {
		print STDERR "Type is $type (not a reaction added or removed); ignoring.\n";
	}

	# Fall through.
} else {
	print STDERR "Has no type; igoring.\n";
}

print CGI->header(-type=>'text/plain');
print "OK\n";
