import hmac
import hashlib


def build_preauth_str(preauth_key, account_name, timestamp, expires,
                      admin=False):
    """ Builds the preauth string and hmac it, following the zimbra spec.

    Spec and examples are here http://wiki.zimbra.com/wiki/Preauth
    """
    if admin:
        s = '{0}|1|name|{1}|{2}'.format(account_name, expires, timestamp)
    else:
        s = '{0}|name|{1}|{2}'.format(account_name, expires, timestamp)

    return hmac.new(preauth_key.encode('utf-8'), s.encode('utf-8'),
                    hashlib.sha1).hexdigest()