import re
import struct
import binascii


def iid_text_to_bin(iid):
    """
    Process an IID and convert to a YARA compliant search string.

    Below describes the GUID structure used to describe an identifier
    for a MAPI interface:

    https://msdn.microsoft.com/en-us/library/office/cc815892.aspx

    :param str iid: Name of the IID to convert

    :return: bin_yara
    :rtype: str
    """

    # remove begin and end brackets
    guid = re.sub('[{}-]', '', iid)
    # convert to binary representation
    bin_struc = struct.unpack("IHH8B", binascii.a2b_hex(guid))
    bin_str = '%.8X%.4X%.4X%s' % \
              (bin_struc[0], bin_struc[1], bin_struc[2],
               (''.join('{:02X}'.format(x) for x in bin_struc[3:])))
    # create YARA compliant search string
    bin_yara = '{ ' + ' '.join(a + b for a, b in
                               zip(bin_str[::2], bin_str[1::2])) + ' }'

    return bin_yara