CREATE OR REPLACE FUNCTION cwmars.clone_action_trigger_event_def_for_org
       (old_def INTEGER, new_owner INTEGER, is_active BOOLEAN DEFAULT TRUE)
RETURNS INTEGER AS
$$
DECLARE
    new_def INTEGER;
BEGIN

INSERT INTO action_trigger.event_definition
(active, owner, name, hook, validator, reactor, cleanup_success, cleanup_failure, delay, max_delay,
 usr_field, opt_in_setting, delay_field, group_field, template, granularity, repeat_delay,
 message_template, message_usr_path, message_library_path, message_title, retention_interval)
SELECT is_active, new_owner, name, hook, validator, reactor, cleanup_success, cleanup_failure,
       delay, max_delay, usr_field, opt_in_setting, delay_field, group_field, template, granularity,
       repeat_delay,message_template, message_usr_path, message_library_path, message_title,
       retention_interval
FROM action_trigger.event_definition
WHERE id = old_def
RETURNING id INTO new_def;

INSERT INTO action_trigger.environment
(event_def, path, collector, label)
SELECT new_def, path, collector, label
FROM action_trigger.environment
WHERE event_def = old_def;

INSERT INTO action_trigger.event_params
(event_def, param, value)
SELECT new_def, param, value
FROM action_trigger.event_params
WHERE event_def = old_def;

RETURN new_def;

END;
$$
LANGUAGE plpgsql;