How can I remove everything from a Commerce cart if a certain product is added, except that product? I'm sure this is pretty simple to do but I'm spacing out on it.

If a product of a certain type is added to the cart, I want to remove everything in the cart , regardless of its type, except for that product. At the same time I need to make sure that the quantity for that product will never exceed 1.

I've started a hook_commerce_cart_product_add() implementation but I haven't got very far with it:

function MYMODULE_commerce_cart_product_add($order, $product, $quantity, $line_item) {
  if ($product-&gt;type == 'the_product_type') {
    // Now what?!
  }
}


I'm more than happy to use Rules instead of custom code for this, but again I haven't got very far trying it that way.

Any pointers would be greatly appreciated.
This is the code I ended up using:

function MYMODULE_commerce_cart_product_add($order, $product, $quantity, $line_item) {
  if ($product-&gt;type == 'directory_subscription') {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

    // Loop through the line items
    foreach ($order_wrapper-&gt;commerce_line_items as $delta =&gt; $line_item_wrapper) {
      // If this is the product we're keeping, make sure the quantity is always 1.
      if ($line_item_wrapper-&gt;commerce_product-&gt;product_id-&gt;value() == $product-&gt;product_id) {
        $line_item_wrapper-&gt;quantity-&gt;set(1);
        $line_item_wrapper-&gt;save();
      }
      else {
        // Remove any other product from the order
        commerce_cart_order_product_line_item_delete($order, $line_item_wrapper-&gt;line_item_id-&gt;value());
      }
    }
  }
}


If anyone has any suggestions on how to improve the above I'd be grateful.