set check_function_bodies = off;

CREATE OR REPLACE FUNCTION public.grp_admins()
 RETURNS grp
 LANGUAGE sql
 STABLE
AS $function$select * from public.grp where tag = public.grp_tag_of_string('admins')$function$
;

CREATE OR REPLACE FUNCTION public.usr_root()
 RETURNS usr
 LANGUAGE sql
 STABLE
AS $function$select * from public.usr where tag = public.usr_tag_of_string('root')$function$
;

CREATE OR REPLACE FUNCTION public.do_insert_usr_perm()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
declare
  admins int;
begin
  admins := public.grp_admins();

  insert into public.perm
    (path, owner_user, owner_group, owner_user_mode, owner_group_mode, everyone_mode)
  values
    ('/users/' || NEW.id || '/tag', NEW.id, admins, 'w', 'w', 'r')
  , ('/users/' || NEW.id || '/email', NEW.id, admins, 'w', 'w', '-')
  , ('/users/' || NEW.id || '/deleted', NEW.id, admins, 'w', 'w', '-')
  , ('/users/' || NEW.id || '/password', NEW.id, admins, 'w', 'w', '-')
  ;

  return new;
end;
$function$
;

CREATE OR REPLACE FUNCTION public.do_usr_create_default_grp()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
declare
  new_grp int;
begin
  insert into public.grp (tag)
  values (grp_tag_of_string('usr_' || new.uid))
  returning id into new_grp;

  perform public.grp_add_member(to_grp => new_grp, add_usr => new.id);

  update public.perm
  set owner_user = public.usr_root()
    , owner_group = public.grp_admins()
  where path = '/groups/' || new_grp || '/members'
     or path = '/groups/' || new_grp || '/tag';

  return null;
end;
$function$
;

CREATE OR REPLACE FUNCTION public.get_acting_usr()
 RETURNS usr
 LANGUAGE plpgsql
AS $function$
declare
  uid text;
  acting_usr public.usr;
begin
  if nullif(current_setting('dnim.usr_uid', true), '') is null then
    acting_usr := public.usr_root();
  else 
    select u.*
    from public.usr u
    where u.uid = current_setting('dnim.usr_uid', true) :: uuid
    into acting_usr;
  end if;

  return acting_usr;
end;
$function$
;

CREATE OR REPLACE FUNCTION public.grp_members_admins()
 RETURNS SETOF usr
 LANGUAGE sql
 STABLE
AS $function$select * from public.grp_members((public.grp_admins()).id)$function$
;
