#!/usr/bin/env perl

use strict;
use warnings;

use IO::Handle;
use IO::Scalar;

use HTTP::Headers;
use HTTP::Request;
use HTTP::Response;
use IO::Socket::SSL qw();
use InterRed::JSON;
use LWP;
use Encode qw(encode_utf8);
use MIME::Base64;

# Proxy script for communication with the Duden Correction Server (DCS).

# Configuration
my %dcs = (
    # Terminate the URL with a /
    url => 'host.docker.internal:8080',
    username => 'duden',
    password => 'duden'
);
# End of configuration

STDIN->blocking(1); 
my $cgi_raw = '';

{ 
  local $/; 
  $cgi_raw = <STDIN>;
  my $s;
  tie  *STDIN, 'IO::Scalar', \$s;
  print STDIN $cgi_raw;
  tied(*STDIN)->setpos(0);
}

use CGI qw /:standard/;

my $q = CGI->new();
my $res;

# XXX: Not verifying SSL certificates is probably a bad idea.
my $ua = LWP::UserAgent->new(
    agent => $q->param('user_agent') || $ENV{HTTP_USER_AGENT},
    ssl_opts => {
        verify_hostname => 0,
        SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE
    },
    request_redirectable => ['GET', 'POST'],
    parse_head => 0
);

my $req;
my $url = $dcs{'url'} . $q->url_param('function');
my $header = ['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 'Authorization' => 'Basic ' . encode_base64($dcs{'username'} . ':' . $dcs{'password'})];

# Forward X-Dks-Uid from the incoming request if present
if (my $x_dks_uid = $ENV{'HTTP_X_DKS_UID'}) {
    $x_dks_uid =~ s/[\r\n]+//g;
    push @$header, ('X-Dks-Uid' => $x_dks_uid);
}

$req = HTTP::Request->new($ENV{REQUEST_METHOD}, $url, $header, $cgi_raw);

$req->header('Expect', '');
$res = $ua->request($req);

print $res->headers()->as_string;
print 'Content-Type: ' . $res->header('content-type') . "\r\n\r\n";
print $res->decoded_content;
