package Amazon::API::Signature4;

use strict;
use warnings;

use parent qw/AWS::Signature4/;

our $VERSION = '1.2.5';

sub new {
  my ( $class, @options ) = @_;
  $class = ref($class) || $class;

  my %args = ref( $options[0] ) ? $options[0] : @options;

  my $self = $class->SUPER::new(%args);

  my @extra = grep { !/access_key|secret_key|security_token/ } keys %args;

  @{$self}{@extra} = @args{@extra};

  return $self;
} ## end sub new

sub _scope {
  my ( $self, $request, $region ) = @_;

  my $host     = $request->uri->host;
  my $datetime = $self->_datetime($request);
  my ($date)   = $datetime =~ /^(\d+)T/;

  my $service = $self->{service};

  if ( !$service || !$region ) {

    if ( $host =~ /^([\w.-]+)\.s3\.amazonaws.com/ ) {    # S3 bucket virtual host
      $service = 's3';
      $region ||= 'us-east-1';
    }
    elsif ( $host =~ /^[\w-]+\.s3-([\w-]+)\.amazonaws\.com/ ) {
      $service = 's3';
      $region ||= $2;
    }
    elsif ( $host =~ /^(\w+)[-.]([\w-]+)\.amazonaws\.com/ ) {
      $service = $1;
      $region ||= $2;
    }
    elsif ( $host =~ /^([\w-]+)\.amazonaws\.com/ ) {
      $service = $1;
    }
  } ## end if ( !$service || !$region)

  if ( !$region ) {
    $region = $self->{region} || 'us-east-1';
  }

  return "$date/$region/$service/aws4_request";
} ## end sub _scope

1;
