USE provisioning;


DROP TRIGGER IF EXISTS voip_phost_crepl_trig;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`sipwise`@`localhost`*/ /*!50003 TRIGGER voip_phost_crepl_trig AFTER INSERT ON voip_peer_hosts
  FOR EACH ROW BEGIN

  DECLARE m_proto CHAR(4);
  IF NEW.transport = 2 THEN
    SET m_proto := 'TCP';
  ELSEIF NEW.transport = 3 THEN
    SET m_proto := 'TLS';
  ELSE
    SET m_proto := 'UDP';
  END IF;

  INSERT INTO voip_peer_preferences (peer_host_id, attribute_id, value)
  SELECT NEW.id, p.id, pe.value
  FROM voip_preferences p, voip_preferences_enum pe
  WHERE p.id <=> preference_id AND p.peer_pref=1 AND pe.peer_pref=1 AND pe.default_val=1 AND pe.value IS NOT NULL;

  IF NEW.enabled THEN
    INSERT INTO kamailio.lcr_gw (id, lcr_id, gw_name, ip_addr, hostname, port, uri_scheme, transport, strip, group_id)
      VALUES(NEW.id, 1, NEW.name, NEW.ip, NEW.host, NEW.port, 1, NEW.transport, 0, NEW.group_id);

    INSERT INTO kamailio.lcr_rule_target (lcr_id, rule_id, gw_id, priority, weight)
           SELECT rule.lcr_id, rule.id, NEW.id, vpg.priority, NEW.weight
             FROM kamailio.lcr_rule rule
             INNER JOIN provisioning.voip_peer_groups vpg ON vpg.id = rule.group_id
            WHERE vpg.id <=> NEW.group_id;

    IF NEW.probe = 1 THEN
      INSERT INTO kamailio.dispatcher (setid, destination, flags, priority, attrs, description)
        VALUES(100, CONCAT('sip:', NEW.ip, ':', NEW.port, ';transport=', m_proto), 8, 0, CONCAT('peerid=', NEW.id, ';peername="', NEW.name, '";peergid=', NEW.group_id, ';'), 'Peer Probe');
    END IF;

  END IF;


  END */;;
DELIMITER ;

INSERT INTO voip_peer_preferences (peer_host_id, attribute_id, value)
SELECT ph.id, p.id, pe.value
  FROM voip_preferences p
  JOIN voip_preferences_enum pe ON pe.preference_id <=> p.id
  JOIN voip_peer_hosts ph
  LEFT OUTER JOIN voip_peer_preferences pp ON pp.attribute_id = p.id AND ph.id = pp.peer_host_id
 WHERE p.peer_pref = 1 AND pe.peer_pref = 1 AND pe.default_val = 1 AND pe.value IS NOT NULL
   AND pp.value IS NULL;
