-- ENV
-- {{ USER_NAME }}
-- {{ USER_PASSWORD }}
-- {{ ORGANIZATION_NAME }}

DO
$do$
BEGIN
   IF EXISTS (
      SELECT FROM pg_catalog.pg_roles
      WHERE rolname = 'role_org_{{ ORGANIZATION_NAME }}') THEN

      RAISE NOTICE 'Role "role_org_{{ ORGANIZATION_NAME }}" already exists. Skipping.';
   ELSE
      BEGIN   -- nested block
         BEGIN
            CREATE ROLE "role_org_{{ ORGANIZATION_NAME }}";
         EXCEPTION
            WHEN duplicate_object THEN
               RAISE NOTICE 'Role "role_org_{{ ORGANIZATION_NAME }}" was just created by a concurrent transaction. Skipping.';
         END;
      END;
   END IF;
END
$do$;


DO
$do$
BEGIN
   IF EXISTS (
      SELECT FROM pg_catalog.pg_roles
      WHERE rolname = '{{ USER_NAME }}') THEN

      RAISE NOTICE 'Role "{{ USER_NAME }}" already exists. Skipping.';
   ELSE
      BEGIN   -- nested block
         BEGIN
            CREATE ROLE "{{ USER_NAME }}" LOGIN PASSWORD '{{ USER_PASSWORD }}';
         EXCEPTION
            WHEN duplicate_object THEN
               RAISE NOTICE 'Role "{{ USER_NAME }}" was just created by a concurrent transaction. Skipping.';
         END;
      END;
   END IF;
END
$do$;

GRANT role_org_{{ ORGANIZATION_NAME }} to {{ USER_NAME }};