 select migrate_aliases();
 select migrate_extensions();
 select migrate_user_group_tree();
+
 select migrate_phone_groups();
 select migrate_folder_values();
 select migrate_non_polycom_phones();
 select migrate_polycom_phones();
 select migrate_phone_group_tree();
 
+select migrate_group_weights();
 select migrate_dialing_plans();
 select migrate_extension_pools();

        usr.display_id);

    -- user group
    insert into user_group (user_id, group_id) values (usr.id, usr.ug_id);

  end loop; 


end;
' language plpgsql;


create or replace function migrate_group_weights() returns integer as '
declare
  my_group record;
  my_weight int := 0;
  next_id int;
begin

  -- default group has the most members and the lowest weight. 
  -- sort by member count descending and assign next weight seq.
  for my_group in 
    select g.group_id as id from user_group ug
      left join group_storage g on ug.group_id = g.group_id
      group by g.group_id order by count(*) desc loop

    update group_storage set weight=my_weight where group_id = my_group.id;
    my_weight := my_weight + 1;

  end loop;

  my_weight := 0;
  for my_group in 
    select g.group_id as id from phone_group pg
      left join group_storage g on pg.group_id = g.group_id
      group by g.group_id order by count(*) desc loop

    update group_storage set weight=my_weight where group_id = my_group.id;
    my_weight := my_weight + 1;

  end loop;

  next_id := max(weight) + 1 from group_storage;
  perform setval(''group_weight_seq'', next_id);

  return 1;
end;
' language plpgsql;


-- U S E R S
create or replace function migrate_users() returns integer as '
declare
