#!/usr/bin/perl
#
# $Id: goproxy.cgi,v 1.1 2004-06-12 04:25:15 atlev Exp $
#
#
# Simple redirection CGI used by FCI DMZ. Two types of
# proxying are dealt with, standard proxying (proxy by
# referrer) or cookiebased proxying.
#
############################################################
  use CGI qw /:standard/;

############################################################
###  VARIABLES
############################################################

  my $query          = new CGI;
  my $type           = $query->param( 'dmzproxytype' );
  my $site           = $query->param( 'dmzproxysite' );
  my $secure_domain  = 'example.api.naiadsystems.com';

  my ( $request_uri, $domain );


############################################################
###  MAIN
############################################################

  # If the proxy type is set to cookie, treat it as such
  # otherwise default to standard proxying.
  if( $type eq 'cookie' )
    {
	$request_uri  = $site;
	$domain       = $site;

	# grab the URI and domain from the site
	$request_uri  =~ s,^(https?://)?[^/]+/?(.*)$,/\2,;
	$domain       =~ s,^(https?://)?([^/]+).*$,\2,;

	# Craft the 'DMZSite' cookie
	#	-expires => '+4h'			,
	my $cookie = $query->cookie(
		-name    => 'DMZSite'			,
		-value   => $domain			,
		-path    => '/'				,
		-domain  => $secure_domain		,
		-secure  => '1'				);

	# Send the cookie and redirect header
        header( 'Access-Control-Allow-Origin: *');
	print $query->header(
		-cookie  => $cookie			,
		-Refresh => "0; URL=$request_uri"	);
    }
  elsif( $type eq 'resetcookie' )
    {
	# Craft an empty 'DMZSite' cookie to reset it
	my $cookie = $query->cookie(
		-name	=> 'DMZSite'			,
		-value  => ''				,
		-path	=> '/'				,
		-domain	=> $secure_domain		,
		-secure	=> '1'				);

	# Send the cookie and redirect header
	print $query->header(
		-cookie  => $cookie			,
		-Refresh => '0; URL=/dmzweb/main.php'	);
    }
  else
    {
	my $proxy  = "https://$secure_domain/proxy/$site";

	# Send the redirect header
	print $query->header(
		-Refresh => "0; URL=$proxy"		);
    }
