\set ON_ERROR_STOP off
\if :{?CONST_SNOWFLAKE_TS_START}
  \warn CONST_SNOWFLAKE_TS_START variable is already set, skipping pg-snowflake.config.sql loading.
\else
  \ir ./pg-snowflake.config.sql
  \if :{?CONST_SNOWFLAKE_TS_START}
    \warn Success! Found pg-snowflake.config.sql, using it.
  \else
    \ir ../pg-snowflake.config.sql
    \if :{?CONST_SNOWFLAKE_TS_START}
      \warn Success! Found ../pg-snowflake.config.sql, using it.
    \else
      \ir ../../pg-snowflake.config.sql
      \if :{?CONST_SNOWFLAKE_TS_START}
        \warn Success! Found ../../pg-snowflake.config.sql, using it.
      \else
        \ir ../../../pg-snowflake.config.sql
        \if :{?CONST_SNOWFLAKE_TS_START}
          \warn Success! Found ../../../pg-snowflake.config.sql, using it.
        \else
          \ir ../../../../pg-snowflake.config.sql
          \if :{?CONST_SNOWFLAKE_TS_START}
            \warn Success! Found ../../../../pg-snowflake.config.sql, using it.
          \else
            \ir ../../../../../pg-snowflake.config.sql
            \if :{?CONST_SNOWFLAKE_TS_START}
              \warn Success! Found ../../../../../pg-snowflake.config.sql, using it.
            \else
              \ir ../../../../../../pg-snowflake.config.sql
              \if :{?CONST_SNOWFLAKE_TS_START}
                \warn Success! Found ../../../../../../pg-snowflake.config.sql, using it.
              \else
                \set ON_ERROR_STOP on
                \set SHOW_CONTEXT never
                DO $$ BEGIN
                  RAISE EXCEPTION 'Could not find pg-snowflake.config.sql in any of the parent directories.';
                END $$;
              \endif
            \endif
          \endif
        \endif
      \endif
    \endif
  \endif
\endif
\set ON_ERROR_STOP on

\ir ./functions/_snowflake_template.sql
\ir ./functions/_snowflake_init.sql

\ir ./functions/snowflake_gen.sql

\set PG_SNOWFLAKE_CLUSTER_NO `echo "$PG_SNOWFLAKE_CLUSTER_NO"`
\set PG_SNOWFLAKE_ISLAND_NO `echo "$PG_SNOWFLAKE_ISLAND_NO"`
SELECT _snowflake_init(
  cluster_no_str := :'PG_SNOWFLAKE_CLUSTER_NO',
  island_no_str := :'PG_SNOWFLAKE_ISLAND_NO'
);

DROP FUNCTION _snowflake_init(text, text);
DROP FUNCTION _snowflake_template(text, text[]);

CREATE SEQUENCE IF NOT EXISTS snowflake_seq
  START WITH 42
  INCREMENT BY 1
  NO MINVALUE
  NO MAXVALUE
  CACHE 1;
