DROP FUNCTION IF EXISTS FORWARDERS_IN ;

DELIMITER |

CREATE FUNCTION FORWARDERS_IN (forewarders_str TEXT,
                                  email_str TEXT,
                                  vacation_domain TEXT ,
                                  list_seperator CHAR ,
                                  vacation_enable BOOLEAN)
   RETURNS TEXT
   DETERMINISTIC
   BEGIN
      DECLARE return_str TEXT;
      DECLARE local_email_part TEXT;
      DECLARE domain_email_part TEXT;


      SET return_str = email_str;

      IF vacation_enable THEN
         SET local_email_part = SUBSTRING(email_str,1, LOCATE('@',email_str) - 1);
         SET domain_email_part = SUBSTRING(email_str, LOCATE('@',email_str) + 1, LENGTH(email_str));
         SET return_str = CONCAT(return_str, list_seperator, local_email_part, "#" ,domain_email_part,"@", vacation_domain);
      END IF;

      IF LENGTH(forewarders_str) > 2 THEN
         SET return_str = CONCAT(return_str, list_seperator, forewarders_str);
      END IF;

      RETURN return_str;
   END |

DELIMITER ;
