ALTER TABLE provisioning.voip_peer_rules DROP COLUMN callee_pattern;
ALTER TABLE provisioning.voip_peer_rules CHANGE COLUMN caller_pattern caller_prefix VARCHAR(64) DEFAULT NULL;

DROP TRIGGER provisioning.voip_prul_crepl_trig;
DROP TRIGGER provisioning.voip_prul_urepl_trig;
DROP TRIGGER provisioning.voip_prul_drepl_trig;

DELIMITER |

CREATE TRIGGER provisioning.voip_prul_crepl_trig AFTER INSERT ON voip_peer_rules
  FOR EACH ROW BEGIN

  INSERT INTO kamailio.lcr_rule (lcr_id, prefix, from_uri, stopper, enabled, group_id)
                          VALUES(1, NEW.callee_prefix, NEW.caller_prefix,
                                 0, 1, NEW.group_id);

  INSERT INTO kamailio.lcr_rule_target (lcr_id, rule_id, gw_id, priority, weight)
         SELECT gw.lcr_id, LAST_INSERT_ID(), gw.id, vpg.priority, vph.weight
           FROM kamailio.lcr_gw gw
           INNER JOIN provisioning.voip_peer_hosts vph ON vph.ip = gw.ip_addr
                                                      AND gw.lcr_id = 1
                                                      AND vph.group_id = gw.group_id
           INNER JOIN provisioning.voip_peer_groups vpg ON vpg.id = vph.group_id
          WHERE vph.group_id = NEW.group_id;

  END;
|

CREATE TRIGGER provisioning.voip_prul_urepl_trig AFTER UPDATE ON voip_peer_rules
  FOR EACH ROW BEGIN

  UPDATE kamailio.lcr_rule
     SET prefix = NEW.callee_prefix, from_uri = NEW.caller_prefix
   WHERE prefix = OLD.callee_prefix
     AND from_uri = OLD.caller_prefix
     AND group_id = OLD.group_id;

  END;
|

CREATE TRIGGER provisioning.voip_prul_drepl_trig AFTER DELETE ON voip_peer_rules
  FOR EACH ROW BEGIN

  DELETE FROM kamailio.lcr_rule
        WHERE prefix = OLD.callee_prefix
          AND from_uri = OLD.caller_prefix
          AND group_id = OLD.group_id;

  -- foreign key will delete from kamailio.lcr_rule_target

  END;
|

DELIMITER ;
