use provisioning;

ALTER TABLE `voip_peer_hosts` ADD COLUMN `dp_caller_in_id` int(11) unsigned NOT NULL;
ALTER TABLE `voip_peer_hosts` ADD COLUMN `dp_callee_in_id` int(11) unsigned NOT NULL;
ALTER TABLE `voip_peer_hosts` ADD COLUMN `dp_caller_out_id` int(11) unsigned NOT NULL;
ALTER TABLE `voip_peer_hosts` ADD COLUMN `dp_callee_out_id` int(11) unsigned NOT NULL;

CREATE TABLE `counter` (
  `name` varchar(64) NOT NULL,
  `value` int(11) unsigned NOT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB;

INSERT INTO counter VALUES('dp_id', 1);

INSERT INTO voip_preferences (attribute, type, dom_pref, data_type, max_occur, internal) VALUES('dp_dom_caller_in', 1, 1, 'int', 1, 1);
INSERT INTO voip_preferences (attribute, type, dom_pref, data_type, max_occur, internal) VALUES('dp_dom_callee_in', 1, 1, 'int', 1, 1);
INSERT INTO voip_preferences (attribute, type, dom_pref, data_type, max_occur, internal) VALUES('dp_dom_caller_out', 1, 1, 'int', 1, 1);
INSERT INTO voip_preferences (attribute, type, dom_pref, data_type, max_occur, internal) VALUES('dp_dom_callee_out', 1, 1, 'int', 1, 1);

DROP TRIGGER voip_dom_drepl_trig;

DELIMITER |

CREATE TRIGGER voip_dom_drepl_trig BEFORE DELETE ON voip_domains
  FOR EACH ROW BEGIN

  DECLARE caller_in_id int(11) unsigned;
  DECLARE callee_in_id int(11) unsigned;
  DECLARE caller_out_id int(11) unsigned;
  DECLARE callee_out_id int(11) unsigned;

  SELECT vdp.value INTO caller_in_id FROM voip_dom_preferences vdp, voip_preferences vp
      WHERE vp.attribute = 'dp_dom_caller_in' AND vdp.attribute_id = vp.id AND vdp.domain_id = OLD.id;
  SELECT vdp.value INTO callee_in_id FROM voip_dom_preferences vdp, voip_preferences vp 
      WHERE vp.attribute = 'dp_dom_callee_in' AND vdp.attribute_id = vp.id AND vdp.domain_id = OLD.id;
  SELECT vdp.value INTO caller_out_id FROM voip_dom_preferences vdp, voip_preferences vp 
      WHERE vp.attribute = 'dp_dom_caller_out' AND vdp.attribute_id = vp.id AND vdp.domain_id = OLD.id;
  SELECT vdp.value INTO callee_out_id FROM voip_dom_preferences vdp, voip_preferences vp 
      WHERE vp.attribute = 'dp_dom_callee_out' AND vdp.attribute_id = vp.id AND vdp.domain_id = OLD.id;

  DELETE FROM kamailio.domain WHERE domain = OLD.domain;
  
  -- work around MySQL bug. the cascaded delete should trigger our
  -- voip_dom_preferences delete action, but doesn't
  DELETE FROM kamailio.dom_preferences WHERE domain = OLD.domain;
  -- this will trigger the delete action for each subscriber
  DELETE FROM provisioning.voip_subscribers WHERE domain_id = OLD.id;
  

  END;
|

DELIMITER ;
