Retrieve a certificate by order_id or certificate_id and write it to stdout or a filename.

    A list of permissible cert_formats is here:
        https://www.digicert.com/services/v2/documentation/appendix-certificate-formats

    CLI Example:

    .. code-block:: bash

        salt-run digicert.get_certificate order_id=48929454 cert_format=apache

    Including a 'filename' will write the certificate to the desired file.
    Note that some cert formats are zipped files, and some are binary.

    If the certificate has not been issued, this function will return the order details
    inside of which will be a status (one of pending, rejected, processing, issued,
    revoked, canceled, needs_csr, and needs_approval)

    If for some reason you want to pipe the output of this command to a file or other
    command you will want to leave off the ``filename`` argument and make sure to include
    ``--no-color`` so there will be no terminal ANSI escape sequences.

def get_certificate(order_id=None, certificate_id=None, minion_id=None, cert_format='pem_all', filename=None):
    '''
    Retrieve a certificate by order_id or certificate_id and write it to stdout or a filename.

    A list of permissible cert_formats is here:
        https://www.digicert.com/services/v2/documentation/appendix-certificate-formats

    CLI Example:

    .. code-block:: bash

        salt-run digicert.get_certificate order_id=48929454 cert_format=apache

    Including a 'filename' will write the certificate to the desired file.
    Note that some cert formats are zipped files, and some are binary.

    If the certificate has not been issued, this function will return the order details
    inside of which will be a status (one of pending, rejected, processing, issued,
    revoked, canceled, needs_csr, and needs_approval)

    If for some reason you want to pipe the output of this command to a file or other
    command you will want to leave off the ``filename`` argument and make sure to include
    ``--no-color`` so there will be no terminal ANSI escape sequences.

    '''

    if order_id:
        order_cert = salt.utils.http.query(
            '{0}/order/certificate/{1}'.format(_base_url(),
                                               order_id),
            method='GET',
            raise_error=False,
            decode=True,
            decode_type='json',
            header_dict={
                'X-DC-DEVKEY': _api_key(),
                'Content-Type': 'application/json',
            }
        )
        if order_cert['dict'].get('status') != 'issued':
            return {'certificate': order_cert['dict']}

        if order_cert['dict'].get('errors', False):
            return {'certificate': order_cert['dict']}

        certificate_id = order_cert['dict'].get('certificate').get('id', None)
        common_name = order_cert['dict'].get('certificate').get('common_name')

    if not certificate_id:
        return {'certificate':
                {'errors':
                    {'code': 'unknown',
                    'message': 'Unknown error, no certificate ID passed on command line or in body returned from API'}}}

    if filename:
        ret_cert = salt.utils.http.query(
            '{0}/certificate/{1}/download/format/{2}'.format(_base_url(),
                                                            certificate_id,
                                                            cert_format),
            method='GET',
            decode=False,
            text=False,
            headers=True,
            text_out=filename,
            raise_error=False,
            header_dict={
                'X-DC-DEVKEY': _api_key(),
            }
    )
    else:
        ret_cert = salt.utils.http.query(
            '{0}/certificate/{1}/download/format/{2}'.format(_base_url(),
                                                            certificate_id,
                                                            cert_format),
            method='GET',
            text=False,
            decode=False,
            raise_error=False,
            header_dict={
                'X-DC-DEVKEY': _api_key(),
            }
    )
    if 'errors' in ret_cert:
        return {'certificate': ret_cert}

    if 'body' not in ret_cert:
        ret = {'certificate': ret_cert}
        cert = ret_cert
    if isinstance(ret_cert, dict):
        ret = ret_cert['body']
        cert = ret
    else:
        ret = ret_cert
        cert = ret

    tmpfilename = None
    if not filename:
        fd, tmpfilename = tempfile.mkstemp()
        filename = tmpfilename
        os.write(fd, cert)
        os.close(fd)

    cmd = ['openssl', 'x509', '-noout', '-subject', '-nameopt', 'multiline', '-in', filename]
    out = subprocess.check_output(cmd)
    common_name = None
    for l in out.splitlines():
        common_name_match = re.search(' *commonName *= *(.*)', l)
        if common_name_match:
            common_name = common_name_match.group(1)
            break
    if tmpfilename:
        os.unlink(tmpfilename)

    if common_name:
        bank = 'digicert/domains'
        cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
        try:
            data = cache.fetch(bank, common_name)
        except TypeError:
            data = {'certificate': cert}
        cache.store(bank, common_name, data)

    if 'headers' in ret_cert:
        return {'certificate': {'filename': filename,
                                 'original_filename': ret_cert['headers'].get('Content-Disposition', 'Not provided'),
                                 'Content-Type': ret_cert['headers'].get('Content-Type', 'Not provided')
                                }}

    return {'certificate': cert}