#!/usr/bin/perl
#
#  ikalog-statink-slack.pl
#  =======================
#
#  Copyright (c) 2016 UMEZAWA Takeshi
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

use utf8;
use strict;
use warnings;
use Getopt::Std;
use Mojo::UserAgent;
use JSON;
use LWP::UserAgent;

STDOUT->autoflush(1);

sub HELP_MESSAGE() {
	print STDERR <<__EOT__;
usage: $0 -s <slack_incoming_webhook_url> [-u <slack_username>] [-c <slack_channel>] [-i <ikalog_websocket_url>]
  -s (required) URL of Slack Incoming WebHook 
  -u (optional) Slack Username
  -c (optional) Slack channel
  -i (optional) URL of IkaLog WebSocket (default: ws://localhost:9090/ws)
__EOT__
	exit(1);
}

my %opts;
$opts{i} = 'ws://localhost:9090/ws';
getopts("i:s:u:c:", \%opts);
if (!defined($opts{s})) {
	HELP_MESSAGE();
}

my $ikalog_url = $opts{i};
my $slack_url = $opts{s};
my $slack_username = $opts{u};
my $slack_channel = $opts{c};

my $lwpua = LWP::UserAgent->new();
my $ua = Mojo::UserAgent->new();

$ua->websocket($ikalog_url => sub {
	my($ua, $tx) = @_;
	print STDERR "Failed to connect websocket\n" and return unless $tx->is_websocket;

	Mojo::IOLoop->stream($tx->connection)->timeout(0);

	$tx->on(finish => sub {
		my($tx, $code, $reason) = @_;
		print STDERR "websocket closed: $code\n";
	});

	$tx->on(message => sub {
		my($tx, $msg) = @_;
		my $jmsg = from_json($msg, { utf8 => 0 });
		my $event = $jmsg->{event};

		if ($event eq "on_output_statink_submission_done") {
			my $url = $jmsg->{response}->{url};
			# 明示的に unfurl_XXX を true にしないと Slack 側が URL を展開してくれないぽい
			my $param = { text => "<$url>", unfurl_links => JSON::true, unfurl_media => JSON::true };
			$param->{username} = $slack_username if defined($slack_username);
			$param->{channel} = $slack_channel if defined($slack_channel);
			print "posting URL $url ...";
			my $res = $lwpua->post($slack_url,
				Content_Type => 'application/json; charset=UTF-8',
				Content => to_json($param, { utf8 => 1 }));
			if ($res->is_success) {
				print " OK\n";
			} else {
				print " ERROR: " . ($res->status_line) . "\n";
			}
		}
	});
});

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
