package Vulture::PostReadRequestHandler;

use strict;
use warnings;
use Apache2::RequestRec ();
use Apache2::ServerRec ();
use Apache2::Connection ();
use APR::SockAddr ();
use Apache2::Const -compile => qw(OK REDIRECT);
use Vulture qw(&get_app $proto &read_conf &get_cookie &session);
use APR::Table;
use Data::Dumper;
sub handler {
	my $r = shift;
	my $url_host;
	my $url_port;
	my $c = $r->connection;
	my $log = $r->server->log;
	my $dbh = DBI->connect($r->dir_config('VultureDSN'));
	my $query = "SELECT if, ip, port, chainfile FROM app, if WHERE app.name='".$r->hostname."' AND app.if=if.id";
	my $sth = $dbh->prepare($query);
	$sth->execute();
	my ($if, $ip, $port, $chainfile) = $sth->fetchrow;
	if ($if) {
	
		if ($ip eq $c->local_addr->ip_get and $port eq $c->local_addr->port) {
			return Apache2::Const::OK;
		}
		else {
			if ($chainfile) {
				$url_host="https";
				if ($port ne "443") {
					$url_port=":".$port;
				}
			}
			else {
				$url_host="http";
				if ($port ne "80") {
					$url_port=":".$port;
				}
			}
			$r->headers_out->set('Location' => $url_host."://". $r->hostname . $url_port);
			$log->debug('Location' => $url_host."://". $r->hostname . $url_port);
			$r->status(Apache2::Const::REDIRECT);
			return Apache2::Const::REDIRECT;
		}
	}
	else {
		return Apache2::Const::OK;
	}
}
1;