# File lib/sup/crypto.rb, line 115
  def decrypt payload # a RubyMail::Message object
    return unknown_status(cant_find_binary) unless @cmd

    payload_fn = Tempfile.new "redwood.payload"
    payload_fn.write payload.to_s
    payload_fn.close

    output_fn = Tempfile.new "redwood.output"
    output_fn.close

    message = run_gpg "--output #{output_fn.path} --yes --decrypt #{payload_fn.path}", :interactive => true

    unless $?.success?
      info "Error while running gpg: #{message}"
      return Chunk::CryptoNotice.new(:invalid, "This message could not be decrypted", message.split("\n"))
    end

    output = IO.read output_fn.path
    output.force_encoding Encoding::ASCII_8BIT if output.respond_to? :force_encoding

    ## there's probably a better way to do this, but we're using the output to
    ## look for a valid signature being present.

    sig = case message
    when /^gpg: (Good signature from .*$)/i
      Chunk::CryptoNotice.new :valid, $1, message.split("\n")
    when /^gpg: (Bad signature from .*$)/i
      Chunk::CryptoNotice.new :invalid, $1, message.split("\n")
    end

    # This is gross. This decrypted payload could very well be a multipart
    # element itself, as opposed to a simple payload. For example, a
    # multipart/signed element, like those generated by Mutt when encrypting
    # and signing a message (instead of just clearsigning the body).
    # Supposedly, decrypted_payload being a multipart element ought to work
    # out nicely because Message::multipart_encrypted_to_chunks() runs the
    # decrypted message through message_to_chunks() again to get any
    # children. However, it does not work as intended because these inner
    # payloads need not carry a MIME-Version header, yet they are fed to
    # RMail as a top-level message, for which the MIME-Version header is
    # required. This causes for the part not to be detected as multipart,
    # hence being shown as an attachment. If we detect this is happening,
    # we force the decrypted payload to be interpreted as MIME.
    msg = RMail::Parser.read output
    if msg.header.content_type =~ %r{^multipart/} && !msg.multipart?
      output = "MIME-Version: 1.0\n" + output
      output.force_encoding Encoding::ASCII_8BIT if output.respond_to? :force_encoding
      msg = RMail::Parser.read output
    end
    notice = Chunk::CryptoNotice.new :valid, "This message has been decrypted for display"
    [notice, sig, msg]
  end