#!perl -w

use strict;
use warnings;

use Qpsmtpd::Constants;

sub register_tests {
    my $self = shift;

    $self->register_test('test_relay_only');
    $self->register_test('test_is_octet_match');
    $self->register_test('test_is_in_cidr_block');
    $self->register_test('test_is_in_norelayclients');
}

sub test_relay_only {
    my $self = shift;

    $self->qp->connection->relay_client(0);
    my $r = $self->relay_only();
    cmp_ok( $r, '==', DENY, "relay_only -");

    $self->qp->connection->relay_client(1);
    $r = $self->relay_only();
    cmp_ok( $r, '==', OK, "relay_only +");

    $self->qp->connection->relay_client(0);
}

sub test_is_octet_match {
    my $self = shift;

    $self->populate_relayclients();

    $self->qp->connection->remote_ip('192.0.1.1');
    ok( $self->is_octet_match(), "match, +");

    $self->qp->connection->remote_ip('192.51.1.1');
    ok( ! $self->is_octet_match(), "nope, -");

    $self->qp->connection->remote_ip('203.0.113.0');
    ok( ! $self->is_octet_match(), "nope, -");
}

sub test_is_in_cidr_block {
    my $self = shift;

    $self->qp->connection->remote_ip('192.0.1.1');
    $self->{_cidr_blocks} = [ '192.0.1.0/24' ];
    ok( $self->is_in_cidr_block(), "match, +" );

    $self->{_cidr_blocks} = [ '192.0.0.0/24' ];
    ok( ! $self->is_in_cidr_block(), "nope, -" );


    $self->qp->connection->remote_ip('fdda:b13d:e431:ae06:00a1::');
    $self->{_cidr_blocks} = [ 'fdda:b13d:e431:ae06::/64' ];
    ok( $self->is_in_cidr_block(), "match, +" );

    $self->{_cidr_blocks} = [ 'fdda:b13d:e431:be17::' ];
    ok( ! $self->is_in_cidr_block(), "nope, -" );
}

sub test_is_in_norelayclients {
    my $self = shift;

    my @matches = qw/ 192.0.99.5 192.0.98.1 192.0.98.255 /;
    my @false = qw/ 192.0.99.7 192.0.109.7 /;

    foreach ( @matches ) {
        $self->qp->connection->remote_ip($_);
        ok( $self->is_in_norelayclients(), "match, + ($_)");
    }

    foreach ( @false ) {
        $self->qp->connection->remote_ip($_);
        ok( ! $self->is_in_norelayclients(), "match, - ($_)");
    }
}