#!/usr/bin/env perl
# Copyright (C) 2017–2021  Alex Schroeder <alex@gnu.org>

# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.

=encoding utf8

=head1 Gemini Chat

This is a test client. All it does is handle repeatedly post stuff to a Gemini
URL. For example, assume that C<gemini://transjovian.org/do/chat/say> is the URL
where you say stuff and C<gemini://transjovian.org/do/chat/listen> is where you
read the chat.

First, generate your client certificate for as many or as few days as you like:

    openssl req -new -x509 -newkey ec -subj "/CN=Alex" \
      -pkeyopt ec_paramgen_curve:prime256v1 -days 100 \
      -nodes -out alex-cert.pem -keyout alex-key.pem

Then start this program to say something:

    gemini-chat --cert=alex-cert.pem --key=alex-key.pem \
      --listen_url=gemini://transjovian.org/do/chat/listen \
      --say_url=gemini://transjovian.org/do/chat/say \

=cut

use Modern::Perl '2018';
use Mojo::IOLoop;
use Pod::Text;
use Getopt::Long;
use Term::ReadLine;
use URI::Escape;
use Encode qw(encode_utf8);

my $cert;
my $key;
my $help;
my $listen_url;
my $say_url;

GetOptions(
  'help' => \$help,
  'cert_file=s' => \$cert,
  'key_file=s' => \$key,
  'listen_url=s' => \$listen_url,
  'say_url=s' => \$say_url)
    or die("Error in command line arguments\n");

# Help
if ($help) {
  my $parser = Pod::Text->new();
  $parser->parse_file($0);
  exit;
}

die "⚠ You must provide --listen_url\n" unless $listen_url;
die "⚠ You must provide --say_url\n" unless $say_url;

my($listen_scheme, $listen_authority, $listen_path, $listen_query, $listen_fragment) =
    $listen_url =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?|;

die "⚠ The URL '$listen_url' must use the gemini scheme\n" unless $listen_scheme and $listen_scheme eq 'gemini';
die "⚠ The URL '$listen_url' must have an authority\n" unless $listen_authority;

my($say_scheme, $say_authority, $say_path, $say_query, $say_fragment) =
    $say_url =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?|;

die "⚠ The URL '$say_url' must use the gemini scheme\n" unless $say_scheme and $say_scheme eq 'gemini';
die "⚠ The URL '$say_url' must have an authority\n" unless $say_authority;

my ($listen_host, $listen_port) = split(/:/, $listen_authority, 2);
$listen_port //= 1965;

my ($say_host, $say_port) = split(/:/, $say_authority, 2);
$say_port //= 1965;

our $pid = fork();

END {
  # client
  if ($pid) {
    kill 'KILL', $pid or warn "Could not kill server $pid";
  }
}

if (!defined $pid) {
  die "Cannot fork: $!";
} elsif ($pid == 0) {
  # Start client for listening
  Mojo::IOLoop->client({
    address => $listen_host,
    port => $listen_port,
    tls => 1,
    tls_cert => $cert,
    tls_key => $key,
    tls_options => { SSL_verify_mode => 0x00 }} => sub {
      my ($loop, $err, $stream) = @_;
      # 1h timeout (for chat)
      $stream->timeout(3600);
      $stream->on(read => sub {
	my ($stream, $bytes) = @_;
	print "\es"; # save cursor position
	print "\e[1G"; # column 1
	print "\n";
	print "\e[1F"; # previous line (on the empty line, now)
	print encode_utf8 $bytes;
	print "\eu" }); # restore cursor position
      $stream->on(close => sub {
	say "\e[31mConnection closed\e[0m"; # red
	exit });
      # Write request to the server
      $stream->write("$listen_url\r\n")});
  # Start event loop if necessary
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
  exit;
}

sleep 1;

# start read loop for saying stuff
my $term = Term::ReadLine->new($say_url);
my $prompt = "> ";
my $OUT = $term->OUT || \*STDOUT;
while (defined ($_ = $term->readline($prompt))) {
  exit if $_ eq "quit";
  # create client
  my $text = uri_escape_utf8($_);
  Mojo::IOLoop->client({
    address => $say_host,
    port => $say_port,
    tls => 1,
    tls_cert => $cert,
    tls_key => $key,
    tls_verify => 0x00, } => sub {
      my ($loop, $err, $stream) = @_;
      $stream->on(read => sub {
	my ($stream, $bytes) = @_;
	if ($bytes =~ /^[123]/) {
	  # Do nothing
	} else {
	  # Print server result
	  print "\e[31m$bytes\e[0m"; # red
	}});
      # Write request to the server
      $stream->write("$say_url?$text\r\n")});
  # Start event loop if necessary
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
  # Add to history
  $term->addhistory($_) if /\S/;
}
