=head1 NAME

App::Parcimonie::GnuPG::Interface - parcimonie's GnuPG::Interface subclass

=head1 SYNOPSIS

Have a look to App::Parcimonie::Daemon for a full-blown real life usage example.

=cut

package App::Parcimonie::GnuPG::Interface;

use Moo;
use MooX::late;
use Carp;
use File::Which qw{which};
use IPC::System::Simple qw{system systemx};

use namespace::clean;

# This child class cannot use MooX::StrictConstructor:
# see "Inheritance" section in its doc for details.

extends 'GnuPG::Interface';

has 'already_torified' => (
    isa      => 'Bool',
    is       => 'rw',
    required => 0,
    default  => sub { 0; },
);

after 'BUILD' => sub {
    my $self = shift;
    unless ($self->already_torified) {
        my $gnupg_homedir = defined $self->options->homedir()
            ? $self->options->homedir()
            : '';
        system(
            q{echo 'use-tor:0:1' | } .
            "GNUPGHOME='$gnupg_homedir' gpgconf --change-options dirmngr " .
            ">/dev/null"
        );
        # Passing --runtime to the previous command does not work,
        # so we have to:
        system("GNUPGHOME='$gnupg_homedir' gpgconf --reload dirmngr");
    }
};

sub get_public_keys_hex {
    my $self = shift;
    my @saved_extra_args = @{$self->options->extra_args()};
    $self->options->push_extra_args(
        '--with-colons',
        '--fixed-list-mode',
        '--with-fingerprint',
        '--with-fingerprint',
        '--with-key-data',
    );

    my $stdin  = IO::Handle->new();
    my $stdout = IO::Handle->new();

    my $handles = GnuPG::Handles->new(
        stdin  => $stdin,
        stdout => $stdout,
    );

    my $pid = $self->wrap_call(
        handles      => $handles,
        commands     => ['--list-public-keys'],
        command_args => [],
    );

    my @returned_keys;
    my $current_primary_key;
    my $current_signed_item;
    my $current_key;
    my $current_pubkey = 0;

    while (<$stdout>) {
        my $line = $_;
        chomp $line;
        my @fields = split ':', $line;

        my $record_type = $fields[0];

        if ( $record_type eq 'pub' ) {
            $current_pubkey = 1;
        }
        elsif ( $record_type eq 'fpr' && $current_pubkey ) {
            next unless @fields > 9;
            push @returned_keys, $fields[9];
            $current_pubkey = 0;
        }
        else {
            $current_pubkey = 0;
        }
    }

    waitpid $pid, 0;

    $self->options->extra_args(\@saved_extra_args);

    return @returned_keys;

}

no Moo;
1; # End of App::Parcimonie::GnuPG::Interface
