package CheckSig;

use FileHandle;

sub new {
    my ($this, $file) = @_;
    my  $class = ref($this) || $this;
    my  $self = {};

    bless($self, $class);
    $self->{"file"} = $file;
    return $self;
}


sub md5ok {
    my( $self, $sum ) = @_;

    unless( $sum ) {
	open( _SUM, "<$self->{'file'}.md5" ) || return undef;
	$sum = <_SUM>;
	close( _SUM );
	$sum =~ s/[\s\t].*//ms;
    }

    my $computed;
    eval {
	require Digest::MD5;
	my $context = new Digest::MD5;
	my $fh = new FileHandle;
	binmode $fh;
	open( $fh, "<$self->{'file'}" );
	while( <$fh> ) {
	    $context->add( $_ );
	}
	close $fh;
	$computed = $context->hexdigest;
    };
    return( ( $computed eq $sum )?1:0 ) if( $computed );

    my( $result, $computed ) = $self->exec_quietly( "md5sum", $self->{'file'} );
    $result && return undef;
    $computed =~ s/[\s\t\r\n].*//ms;
    return( ( $computed eq $sum ) ? 1:0 );
}



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

    my $keyring = "$BigSister::common::fs{'etc'}/keys";
    ( -f "$self->{'file'}.sig" ) || return undef;
    my( $result, $text ) = $self->exec_quietly( "gpg", "--version" );
    $result && return undef;
    my( $result, $text ) = $self->exec_quietly( "gpg", "--verify", "--keyring", "$keyring", "$self->{'file'}.sig" );
    return( $result?0:1 );
}



sub exec_quietly {
    my( $self, @cmd ) = @_;

    my $sub = new FileHandle();
    my $pid = open( $sub, "-|" );
    if( $pid ) {
	my $text = "";
	while( <$sub> ) {
	    $text .= $_;
	}
	close $sub;
	return( $?, $text );
    }
    elsif( defined $pid ) {
	close STDERR;
	open( STDERR, ">/dev/null" );
	exec( @cmd );
	exit(1);
    }
    return( 256 );
}

1;

