#!/usr/bin/env perl

# This is a simple script to proxy Qt CI remote API requests from testresults.qt-project.org
# to the host on which the integrator is running (which is usually not Internet-accessible).
#
# This is essentially a one-off special case of Apache's mod_proxy.
use strict;
use warnings;

use CGI;
use LWP::UserAgent;
use URI;

# Real URI of the CI remote API.
# In our case, we expect that the CI host has connected to us and forwarded a port
# via e.g. "ssh -R 7181:127.0.0.1:7181 -N qtintegration@testresults.qt-project.org",
# hence 127.0.0.1 for the host.
my $PROXY_TO = 'http://127.0.0.1:7181/api/json';

# Headers we permit proxying from client to server
my @PERMITTED_CLIENT_HEADERS = qw(
    Accept
    Accept-Charset
    Accept-Encoding
    User-Agent
);

# Headers we permit proxying from server to client
my @PERMITTED_SERVER_HEADERS = qw(
    Access-Control-Allow-Origin
    Cache-Control
    Client-Date
    Content-Encoding
    Content-Length
    Content-Type
    Expires
);

# Entry point
sub run
{
    # we proxy the query string unmodified, and the permitted subset of headers both ways.

    my $uri = URI->new( $PROXY_TO );
    $uri->query( $ENV{ QUERY_STRING } );

    my %req_headers;
    foreach my $http_header (@PERMITTED_CLIENT_HEADERS) {
        my $val = CGI->http( $http_header );
        if (defined $val) {
            $req_headers{ $http_header } = $val;
        }
    }

    my $ua = LWP::UserAgent->new();
    my $response = $ua->get( $uri, %req_headers );

    my %resp_headers = (
        -status => $response->status_line()
    );
    foreach my $http_header (@PERMITTED_SERVER_HEADERS) {
        my $val = $response->header( $http_header );
        if (defined $val) {
            # note leading - character, see 'perldoc CGI'
            $resp_headers{ "-$http_header" } = $val;
        }
    }

    print CGI->header( %resp_headers )
         .$response->content();

    return;
}

run() unless caller;
1;
