#!/usr/bin/perl

use strict;
use warnings;
use File::Basename;
use lib dirname (__FILE__);
use TestUtils;
use TestHTTPD;
use File::Temp;
use IO::Socket::INET;

sub proxy {
    my $config = shift;

    exec(@_, '../src/sniproxy', '-f', '-c', $config);
}

sub make_fallback_config($$$) {
    my $proxy_port = shift;
    my $httpd_port = shift;
    my $fallback_port = shift;

    my ($fh, $filename) = File::Temp::tempfile();
    my ($unused, $logfile) = File::Temp::tempfile();

    # Write out a test config file
    print $fh <<END;
# Minimal fallback test configuration

listen 127.0.0.1 $proxy_port {
    proto http
    fallback 127.0.0.1:$fallback_port
    access_log $logfile
}

table {
    localhost 127.0.0.1 $httpd_port
}
END

    close ($fh);

    return $filename;
}

sub http10_client($$) {
    my $path = shift;
    my $port = shift;

    my $socket = IO::Socket::INET->new(PeerAddr => '127.0.0.1',
                                       PeerPort => $port,
                                       Proto => "tcp",
                                       Type => SOCK_STREAM)
        or die "couldn't connect $!";

    $socket->send("GET /$path HTTP/1.0\r\n\r\n");

    my $buffer;
    $socket->recv($buffer, 4096);

    $socket->close();

    # Expect fallback HTTP server 203 rather than 200 from main test HTTPD instance
    return "Unexpected response: $buffer\n" unless $buffer =~ /\AHTTP\/1\.1 203/;

    return undef;
}

sub worker($$) {
    my ($hostname, $path, $port, $requests) = @_;

    for (my $i = 0; $i < $requests; $i++) {
        my $error = http10_client($path, $port);

        die $error if defined $error;
    }
    # Success
    exit 0;
}

sub main {
    my $proxy_port = $ENV{SNI_PROXY_PORT} || 8080;
    my $httpd_port = $ENV{TEST_HTTPD_PORT} || 8081;
    my $fallback_port = $ENV{TEST_FALLBACK_PORT} || 8082;
    my $workers = $ENV{WORKERS} || 10;
    my $iterations = $ENV{ITERATIONS} || 10;
    my $local_httpd = $ENV{LOCAL_HTTPD_PORT};

    my $config = make_fallback_config($proxy_port, $local_httpd || $httpd_port, $fallback_port);
    my $proxy_pid = start_child('server', \&proxy, $config, @ARGV);
    my $httpd_pid = start_child('server', \&TestHTTPD::httpd, port => $httpd_port) unless $local_httpd;
    my $fallback_httpd_pid = start_child('server', \&TestHTTPD::httpd, port => $fallback_port, generator => sub {
            return sub($) {
                my $sock = shift;

                print $sock "HTTP/1.1 203 Non-Authoritative Information\r\n";
                print $sock "Server: TestHTTPD/$TestHTTPD::VERSION\r\n";
                print $sock "Content-Type: text/plain\r\n";
                print $sock "Content-Length: 15\r\n";
                print $sock "Connection: close\r\n";
                print $sock "\r\n";
                print $sock "Fallback server";
            }
        });

    # Wait for proxy to load and parse config
    wait_for_port(port => $httpd_port);
    wait_for_port(port => $proxy_port);
    wait_for_port(port => $fallback_port);

    for (my $i = 0; $i < $workers; $i++) {
        start_child('worker', \&worker, 'nonexistant.host', '', $proxy_port, $iterations);
    }

    # Wait for all our children to finish
    wait_for_type('worker');

    # Give the proxy a second to flush buffers and close server connections
    sleep 1;

    # Orderly shutdown of the server
    kill 15, $proxy_pid;
    kill 15, $httpd_pid unless $local_httpd;
    kill 15, $fallback_httpd_pid;
    sleep 1;

    # Delete our test configuration
    unlink($config);

    # Kill off any remaining children
    reap_children();
}

main();
