// EndpointGroupUpdate updates endpoint group
func (ac *APIController) EndpointGroupUpdate(endpointGroup, params *contivModel.EndpointGroup) error {
	log.Infof("Received EndpointGroupUpdate: %+v, params: %+v", endpointGroup, params)

	// Only update policy attachments

	// Look for policy adds
	for _, policyName := range params.Policies {
		if !stringInSlice(policyName, endpointGroup.Policies) {
			policyKey := endpointGroup.TenantName + ":" + policyName

			// find the policy
			policy := contivModel.FindPolicy(policyKey)
			if policy == nil {
				log.Errorf("Could not find policy %s", policyName)
				return core.Errorf("Policy not found")
			}

			// attach policy to epg
			err := master.PolicyAttach(endpointGroup, policy)
			if err != nil && err != master.EpgPolicyExists {
				log.Errorf("Error attaching policy %s to epg %s", policyName, endpointGroup.Key)
				return err
			}

			// Setup links
			modeldb.AddLinkSet(&policy.LinkSets.EndpointGroups, endpointGroup)
			modeldb.AddLinkSet(&endpointGroup.LinkSets.Policies, policy)
			err = policy.Write()
			if err != nil {
				return err
			}
		}
	}

	// now look for policy removals
	for _, policyName := range endpointGroup.Policies {
		if !stringInSlice(policyName, params.Policies) {
			policyKey := endpointGroup.TenantName + ":" + policyName

			// find the policy
			policy := contivModel.FindPolicy(policyKey)
			if policy == nil {
				log.Errorf("Could not find policy %s", policyName)
				return core.Errorf("Policy not found")
			}

			// detach policy to epg
			err := master.PolicyDetach(endpointGroup, policy)
			if err != nil && err != master.EpgPolicyExists {
				log.Errorf("Error detaching policy %s from epg %s", policyName, endpointGroup.Key)
				return err
			}

			// Remove links
			modeldb.RemoveLinkSet(&policy.LinkSets.EndpointGroups, endpointGroup)
			modeldb.RemoveLinkSet(&endpointGroup.LinkSets.Policies, policy)
			err = policy.Write()
			if err != nil {
				return err
			}
		}
	}

	// Update the policy list
	endpointGroup.Policies = params.Policies

	return nil
}