#------------------------------------------------------------
# Copyright (C) 2008 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RSApache::Command::InternalCommand;

use strict;

#use warnings;

use CGI;
use URI::Escape;
use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::Log;
use Common::RSApp;
use RSApache::RSWebApp;
use RSApache::Command;

use base 'RSApache::Command';

my @IP_BASE_OK = qw(67.52.158 10.10.10 172.24.1 127.0.0 38.100.237);

#my $USER_AGENT_OK = 'RS-Request';

sub _init {
    my ($self) = @_;

    # Let the inherited initialization happen.
    #
    $self->SUPER::_init();

    # Going to assume that if we have a cgi object, then we're executing in
    # a regular web app environment, and we're handing a web request.
    # Which means that it makes sense to do our test of the requestor ip address.
    #
    # If we _don't_ have a cgi, then this command has been created in a different
    # context (say, as a 'internal redirect' from another command), and therefore
    # we don't necessarily want or need to do this check.
    # We'll see how that works out...

    my $cgi = $self->getCGI();
    if ( defined $cgi && !$self->_requestorIsLocal($cgi) ) {

        # Just throw an exception.
        #
        die "ERROR - Requestor IP is not on our local subnet";
    }

    # since clientID isn't in the env, set it from the cgi args
    my $clientID = $self->getParam('client_id');
    $self->{_RSAPP} = Common::RSApp->new_temporary( clientID => $clientID ) if ( $clientID >= 0 );

    return $self;
}

# Broke this out into its own method so we can override it if necessary.
#
sub _requestorIsLocal {
    my ( $self, $cgi ) = @_;

    my $ip = $cgi->remote_host();
    $ip =~ s/\.\d+$//;

    #my $agent = $cgi->user_agent();
    #return 1 if (grep (/^$ip$/, @IP_BASE_OK) && $agent eq $USER_AGENT_OK);
    return 1 if ( grep /^$ip$/, @IP_BASE_OK );
    return 0;
}

###
1;    # Play nicely.
###
