# attempt to check PGP signature in a RFC3156-compliant way
module TMail
  class Mail
    def is_pgp_signed?
	content_type == "multipart/signed" and parts.size == 2 and parts[1].content_type == "application/pgp-signature"
    end

    def pgp_signature
      return nil unless is_pgp_signed?
      parts[1].decoded
    end

    def pgp_signed_part
      return nil unless is_pgp_signed?
      parts[0]
    end

    def verify_pgp_signature
      return nil unless is_pgp_signed?

      # using RAW part, without any decoding
      # remove last EOL due to MIME protocol and properly convert all EOL to CRLF
      content = parts[0].raw.chomp.gsub(/\r?\n/, "\r\n")
      sig = pgp_signature()

      sig_check = nil
      GPGME::verify(sig, content) do |signature|
        sig_check = signature
      end

      sig_check
    end

    protected

    def raw
      @port.read_all
    end
  end
end
