#!/usr/bin/env perl

use strict;
use warnings;

use FindBin qw($Bin);
use Getopt::Long qw(GetOptions);
use Time::HiRes qw(time);

use lib "$Bin/../lib";

my $iterations = 210_000;
my $runs       = 5;
my $help       = 0;
GetOptions(
    'iterations=i' => \$iterations,
    'runs=i'       => \$runs,
    'help'         => \$help,
) or die _usage();
if ($help) {
    print _usage();
    exit 0;
}
die _usage() if @ARGV || $iterations < 1 || $iterations > 2_147_483_647;
die "--runs must be an odd positive integer\n" if $runs < 1 || $runs % 2 == 0;

require Digest::SHA;
require Developer::Dashboard::Crypto::PBKDF2;

die "OpenSSL XS PBKDF2 backend is unavailable\n"
  if !Developer::Dashboard::Crypto::PBKDF2->native_available;

my $password = 'problem48-password';
my $salt     = 'problem48-salt';
my $known    = unpack 'H*', _pbkdf2_perl( $password, $salt, 1 );
my $xs_one = Developer::Dashboard::Crypto::PBKDF2->derive_sha256(
    password   => $password,
    salt       => $salt,
    iterations => 1,
);
die "OpenSSL XS PBKDF2 digest mismatch\n" if !defined $xs_one || $xs_one ne $known;

my ( @perl_seconds, @xs_seconds );
for ( 1 .. $runs ) {
    my $started = time;
    my $perl = unpack 'H*', _pbkdf2_perl( $password, $salt, $iterations );
    push @perl_seconds, time - $started;

    $started = time;
    my $xs = Developer::Dashboard::Crypto::PBKDF2->derive_sha256(
        password   => $password,
        salt       => $salt,
        iterations => $iterations,
    );
    push @xs_seconds, time - $started;

    die "PBKDF2 output mismatch during benchmark run $_\n" if !defined $xs || $xs ne $perl;
}

my $perl_median = _median(@perl_seconds);
my $xs_median   = _median(@xs_seconds);
printf "PBKDF2-HMAC-SHA256: %d iterations, %d alternating runs; all_digests_match=yes\n",
  $iterations, $runs;
printf "Perl median_ms=%.3f XS median_ms=%.3f (%.2fx)\n",
  1000 * $perl_median, 1000 * $xs_median, $perl_median / $xs_median;
exit 0;

# _usage()
# Returns the benchmark's options and validation synopsis.
# Input: none.
# Output: usage text string.
sub _usage {
    return "Usage: $0 [--iterations N] [--runs ODD_N] [--help]\n";
}

# _pbkdf2_perl($password, $salt, $rounds)
# Computes one-block PBKDF2-HMAC-SHA256 using the established Digest::SHA loop.
# Input: password bytes, salt bytes, and positive round count.
# Output: raw 32-byte derived key.
sub _pbkdf2_perl {
    my ( $password_bytes, $salt_bytes, $rounds ) = @_;
    my $u      = Digest::SHA::hmac_sha256( $salt_bytes . pack( 'N', 1 ), $password_bytes );
    my $result = $u;
    for ( 2 .. $rounds ) {
        $u = Digest::SHA::hmac_sha256( $u, $password_bytes );
        $result ^= $u;
    }
    return $result;
}

# _median(@seconds)
# Returns the middle sample for an odd, nonempty timing list.
# Input: elapsed-second values.
# Output: median elapsed seconds.
sub _median {
    my @samples = sort { $a <=> $b } @_;
    die "Cannot calculate a median without samples\n" if !@samples;
    return $samples[ int( @samples / 2 ) ];
}

__END__

=pod

=head1 NAME

problem48-inline-xs-benchmark - compare PBKDF2 Perl and XS

=head1 PURPOSE

Measures the same PBKDF2-HMAC-SHA256 input through the existing Perl
Digest::SHA reference loop and the Dashboard XS adapter around OpenSSL's
PBKDF2 function.

=head1 WHY IT EXISTS

Problem 48 uses this benchmark to compare the production XS path with the
established Perl reference loop. Every timed digest must match exactly before
the medians are reported.

=head1 WHEN TO USE

Use in the development container after building the Dashboard XS extension.
This script is research tooling and is not loaded by the application.

=head1 HOW TO USE

  perl script/problem48-inline-xs-benchmark
  perl script/problem48-inline-xs-benchmark --iterations 1000 --runs 3

The default uses the production 210,000-round work factor and five alternating
runs. The sample count must be odd and positive; every implementation must
produce byte-identical output or the script fails.

=head1 WHAT USES IT

Problem 48 performance research uses this benchmark to compare Perl and XS
PBKDF2 execution. The dashboard and release process do not invoke it.

=head1 EXAMPLES

  PERL5LIB=/bench-perl/lib/perl5:/bench-perl/lib/perl5/x86_64-linux-gnu-thread-multi perl script/problem48-inline-xs-benchmark

  d2 docker compose -p dd-problem48-bench -f /tmp/d2-problem48-bench.yml -f /tmp/d2-problem48-init.yml run --rm bench sh -lc 'cd /checkout && PERL5LIB=/bench-perl/lib/perl5:/bench-perl/lib/perl5/x86_64-linux-gnu-thread-multi perl script/problem48-inline-xs-benchmark'

=cut
