/**
 * Implementation of hook_civicrm_pre
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_pre
 */
function mailchimp_civicrm_pre($op, $objectName, $id, &$params)
{
    $params1 = array('version' => 3, 'sequential' => 1, 'contact_id' => $id, 'id' => $id);
    if ($objectName == 'Email') {
        $email = new CRM_Core_BAO_Email();
        $email->id = $id;
        $email->find(TRUE);
        // If about to delete an email in CiviCRM, we must delete it from Mailchimp
        // because we won't get chance to delete it once it's gone.
        //
        // The other case covered here is changing an email address's status
        // from for-bulk-mail to not-for-bulk-mail.
        // @todo Note: However, this will delete a subscriber and lose reporting
        // info, where what they might have wanted was to change their email
        // address.
        if ($op == 'delete' || $op == 'edit' && $params['on_hold'] == 0 && $email->on_hold == 0 && $params['is_bulkmail'] == 0) {
            CRM_Mailchimp_Utils::deleteMCEmail(array($id));
        }
    }
    // If deleting an individual, delete their (bulk) email address from Mailchimp.
    if ($op == 'delete' && $objectName == 'Individual') {
        $result = civicrm_api('Contact', 'get', $params1);
        foreach ($result['values'] as $key => $value) {
            $emailId = $value['email_id'];
            if ($emailId) {
                CRM_Mailchimp_Utils::deleteMCEmail(array($emailId));
            }
        }
    }
}