;; -*- emacs-lisp -*-
(defun mc-gpg-lookup-public-key (str &optional type)
  ;; Look up the string STR in the user's secret key ring.  Return a
  ;; pair of strings (USER-ID . KEY-ID) which uniquely identifies the
  ;; matching key, or nil if no key matches.
  (let (args)
    (if (string= str "***** CONVENTIONAL *****") nil
      (let ((result (cdr-safe (assoc str mc-gpg-key-cache)))
            (key-regexp
             "^\\(sec\\|pub\\):[^:]*:[^:]*:[^:]*:\\([^:]*\\):[^:]*:[^:]*:[^:]*:[^:]*:\\([^:]*\\):"
             )
            (obuf (current-buffer))
            buffer)
        (if (null result)
            (unwind-protect
                (progn
                  (setq buffer (generate-new-buffer " *mailcrypt temp"))
                  (setq args (list
                              "--with-colons"
                              "--no-greeting" "--batch"
                              "--list-public-keys" str
                              ))
                  (if mc-gpg-alternate-keyring
                      (setq args (append (list "--keyring"
                                               mc-gpg-alternate-keyring)
                                         args)))
                  (if mc-gpg-extra-args
                      (setq args (append mc-gpg-extra-args args)))
                  (mc-gpg-debug-print
                   (format "lookup: args are %s" args))
                  (let ((coding-system-for-read
                         (if (and (fboundp 'coding-system-p)
                                  (coding-system-p 'utf-8))
                             'utf-8 nil)))
                    (apply 'call-process mc-gpg-path nil buffer nil args))
                  (set-buffer buffer)
                  (goto-char (point-min))
                  (if (re-search-forward key-regexp nil t)
                      (progn
                        (setq result
                              (cons (buffer-substring-no-properties
                                     (match-beginning 3) (match-end 3))
                                    (concat
                                     "0x"
                                     (buffer-substring-no-properties
                                      (match-beginning 2) (match-end 2)))))
                        (setq mc-gpg-key-cache (cons (cons str result)
                                                     mc-gpg-key-cache)))))
                                        ;(if buffer (kill-buffer buffer))
              (set-buffer obuf)))
        (if (null result)
            (error "No GPG public key for %s" str))
        result))))


(defun mml2015-mailcrypt-encrypt (cont &optional sign)
  "modified version which checks that a key is valid before attempting to
encrypt with it"
  (let ((new-recipients)
        (mc-pgp-always-sign
         (or mc-pgp-always-sign
             sign
             (eq t (or (message-options-get 'message-sign-encrypt)
                       (message-options-set
                        'message-sign-encrypt
                        (or (y-or-n-p "Sign the message? ")
                            'not))))
             'never)))
    (setq new-recipients (message-options-get 'message-recipients))
    (mm-with-unibyte-current-buffer-mule4
      (mc-encrypt-generic
       (or
        (and (message-options-get 'message-recipients)

             (if (member nil (mapcar
                              (lambda (addy)
                                (condition-case nil
                                    (progn
                                      (when (mc-gpg-lookup-public-key addy) t))
                                  (error nil)))
                              (mc-split ",[\n\t ]?" (message-options-get
                                                     'message-recipients))))
                 nil
               (message-options-get 'message-recipients)))

        (while (member nil (mapcar
                            (lambda (addy)
                              (condition-case nil
                                  (progn
                                    (mc-gpg-lookup-public-key addy))
                                (error nil)))
                            (mc-split ",[\n\t ]?"
                                      (setq new-recipients
                                            (read-string "Recipients: "
                                                         new-recipients))))))

        (message-options-set 'message-recipients new-recipients))

       nil nil nil
       (message-options-get 'message-sender))))
  (goto-char (point-min))
  (unless (looking-at "-----BEGIN PGP MESSAGE-----")
    (error "Fail to encrypt the message"))
  (let ((boundary
         (funcall mml-boundary-function (incf mml-multipart-number))))
    (insert (format "Content-Type: multipart/encrypted; boundary=\"%s\";\n"
                    boundary))
    (insert "\tprotocol=\"application/pgp-encrypted\"\n\n")
    (insert (format "--%s\n" boundary))
    (insert "Content-Type: application/pgp-encrypted\n\n")
    (insert "Version: 1\n\n")
    (insert (format "--%s\n" boundary))
    (insert "Content-Type: application/octet-stream\n\n")
    (goto-char (point-max))
    (insert (format "--%s--\n" boundary))
    (goto-char (point-max))))
