use strict;
use warnings;
use ExtUtils::Constant 0.23 qw(WriteConstants autoload);
use ExtUtils::MakeMaker qw(WriteMakefile);

# Work around a problem in ExtUtils::Constant::ProxySubs which
# generates code not working with perl<5.14.
# https://rt.cpan.org/Public/Bug/Display.html?id=124074
my $USE_PROXYSUBS = $^V gt v5.14.0;
my $CAT = $^O eq 'MSWin32' ? 'type' : 'cat';
my $SEP = $^O eq 'MSWin32' ? ''     : '"';
do {
    open my $fh, '>', 'const-autoload.inc'
      or die $!;

    if (!$USE_PROXYSUBS) {
        print {$fh} "use Carp qw(croak);\n";
        print {$fh} autoload('Crypt::SMIME'), "\n";
    }
};

WriteMakefile(
    NAME                => 'Crypt::SMIME',
    AUTHOR              => 'Ymirlink <tl@tripletail.jp>',
    VERSION_FROM        => 'SMIME.pl',
    ABSTRACT            => 'S/MIME message signing, verification, encryption and decryption',
    PL_FILES            => {},
    CONFIGURE_REQUIRES  => {
        'ExtUtils::CChecker'  => 0,
        'ExtUtils::Constant'  => '0.23',
        'ExtUtils::MakeMaker' => 0,
        'ExtUtils::PkgConfig' => 0,
    },
    PREREQ_PM           => {
        'XSLoader'      => 0,
    },
    BUILD_REQUIRES      => {
        'ExtUtils::PkgConfig' => 0,
        'Test::Exception'     => 0,
        'Test::More'          => 0,
    },
    CONFIGURE           => sub {
        require ExtUtils::CChecker;
        require ExtUtils::PkgConfig;

        local $|  = 1;
        my    $cc = ExtUtils::CChecker->new();

        print 'checking for gettimeofday... ';
        my $HAVE_GETTIMEOFDAY = $cc->try_compile_run(<<'EOF');
#include <sys/time.h>
int main(int argc, char* argv[]) {
    struct timeval tv;
    gettimeofday(&tv, (struct timezone*)0);
    return 0;
}
EOF
        my $HAVE_SYS_TIME_H = $HAVE_GETTIMEOFDAY;
        print ($HAVE_GETTIMEOFDAY ? "yes\n" : "no\n");

        print 'checking for time... ';
        my $HAVE_TIME = $cc->try_compile_run(<<'EOF');
#include <time.h>
int main(int argc, char* argv[]) {
    time_t t;
    t = time((time_t*)0);
    return 0;

}
EOF
        my $HAVE_TIME_H = $HAVE_TIME;
        print ($HAVE_TIME ? "yes\n" : "no\n");

        my ($LIBCRYPTO_CFLAGS, $LIBCRYPTO_LIBS) = do {
            if (exists $ENV{LIBCRYPTO_CFLAGS} && exists $ENV{LIBCRYPTO_LIBS}) {
                ($ENV{LIBCRYPTO_CFLAGS}, $ENV{LIBCRYPTO_LIBS});
            }
            else {
                print 'checking for libcrypto... ';
                # CMS support was introduced in 0.9.8
                # CMS_STREAM was introduced in 0.9.9
                my %LIBCRYPTO = ExtUtils::PkgConfig->find('libcrypto >= 0.9.9');
                print "$LIBCRYPTO{modversion}\n";

                ($LIBCRYPTO{cflags}, $LIBCRYPTO{libs});
            }
        };
        print "checking for LIBCRYPTO_CFLAGS... $LIBCRYPTO_CFLAGS\n";
        print "checking for LIBCRYPTO_LIBS... $LIBCRYPTO_LIBS\n";

        return +{
            INC  => join(' ',
                         $LIBCRYPTO_CFLAGS,
                         '-DOPENSSL_LOAD_CONF',
                         $HAVE_GETTIMEOFDAY ? ('-DHAVE_GETTIMEOFDAY') : (),
                         $HAVE_SYS_TIME_H   ? ('-DHAVE_SYS_TIME_H'  ) : (),
                         $HAVE_TIME         ? ('-DHAVE_TIME'        ) : (),
                         $HAVE_TIME_H       ? ('-DHAVE_TIME_H'      ) : ()),
            LIBS => $LIBCRYPTO_LIBS,
        };
    },
    dist                => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', },
    clean               => { FILES => 'Crypt-SMIME-*' },
    realclean           => { FILES => 'const-*.inc' },
    PM                  => {
        'lib/SMIME.pm'     => '$(INST_LIBDIR)/SMIME.pm',
        'lib/SMIME/JA.pod' => '$(INST_LIBDIR)/SMIME/JA.pod',
    },
    depend              => {
        'lib/SMIME.pm'
          => "SMIME.pl SMIME.pod const-autoload.inc\n" .
             ( -d 'lib' ? '' : "\tmkdir lib\n") .
             "\techo $SEP# This file is automatically generated from SMIME.pl$SEP           > \$\@\n" .
             "\techo $SEP# All of your changes will be lost if you edit this directly.$SEP >> \$\@\n" .
             "\t$CAT SMIME.pl  >> \$\@\n" .
             "\t$CAT const-autoload.inc >> \$\@\n" .
             "\techo #        >> \$\@\n" .
             "\techo __END__  >> \$\@\n" .
             "\techo #        >> \$\@\n" .
             "\t$CAT SMIME.pod >> \$\@\n",

        'SMIME.pod'
          => "SMIME.mlpod\n" .
             "\tmlpod2pod \$< > \$\@",

        'lib/SMIME/JA.pod'
          => "SMIME.mlpod\n" .
             ( -d 'lib'       ? '' : "\tmkdir lib\n") .
             ( -d 'lib/SMIME' ? '' : "\tmkdir lib/SMIME\n") .
             "\tmlpod2pod --langs=ja \$< | perl -pe 's/(\\xe5\\x90\\x8d\\xe5\\x89\\x8d)/NAME/' > \$\@",
    },
);

WriteConstants(
    NAME  => 'Crypt::SMIME',
    NAMES => [
        {name => 'NO_CHECK_CERTIFICATE', macro => 'CMS_NO_SIGNER_CERT_VERIFY', value => 'CMS_NO_SIGNER_CERT_VERIFY'},

        {name => 'FORMAT_ASN1' , macro => 1, value => 'CRYPT_SMIME_FORMAT_ASN1' },
        {name => 'FORMAT_PEM'  , macro => 1, value => 'CRYPT_SMIME_FORMAT_PEM'  },
        {name => 'FORMAT_SMIME', macro => 1, value => 'CRYPT_SMIME_FORMAT_SMIME'}
       ],
    ($USE_PROXYSUBS ?
       (PROXYSUBS => {autoload => 1}) : ())
   );