CREATE LANGUAGE plpgsql;


DROP FUNCTION IF EXISTS udf_forwarders_in();
DROP FUNCTION IF EXISTS udf_forwarders_in(TEXT,TEXT,TEXT,CHAR,BOOLEAN);

CREATE FUNCTION udf_forwarders_in(forewarders_str TEXT,
                                  email_str TEXT,
                                  vacation_domain TEXT ,
                                  list_seperator CHAR ,
                                  vacation_enable BOOLEAN) 
   RETURNS TEXT AS $$
   DECLARE
      return_str text;
      local_email_part TEXT;
      domain_email_part TEXT;
   BEGIN

      return_str = email_str;

      IF vacation_enable THEN
        local_email_part = substring(email_str, 1, position('@' in email_str) - 1);
        domain_email_part = substring(email_str,  position('@' in email_str) + 1 );
        return_str = return_str || list_seperator || local_email_part || '#' || domain_email_part || '@' || vacation_domain; 
      END IF;

      IF char_length(forewarders_str) > 7 THEN
         return_str = return_str || list_seperator || forewarders_str;
      END IF;

      RETURN return_str;
   END;
   $$ LANGUAGE plpgsql;


SELECT udf_forwarders_in('ckubu@oopen.de', 'admin@initiativenserver.de','autoreply.initiativenserver.de',',',TRUE);
