#!/bin/bash
set -e
source env.sh

echo "🔗 Ühendan kõik links_* tabelid skeemist ${destination_schema}"

psql ${CONNECTION_NAME} -d ${destination_dbname} <<EOF
DO \$\$
DECLARE
  schema_name text := '${destination_schema}';
  r record;
BEGIN
  EXECUTE format('DROP TABLE IF EXISTS %I.links CASCADE', schema_name);
  EXECUTE format('CREATE TABLE %I.links (LIKE %I.links_Saare INCLUDING ALL)', schema_name, schema_name);

  FOR r IN
    EXECUTE format('SELECT tablename FROM pg_tables WHERE schemaname = %L AND tablename LIKE %L', schema_name, 'links_%')
  LOOP
    EXECUTE format('INSERT INTO %I.links SELECT * FROM %I.%I', schema_name, schema_name, r.tablename);
  END LOOP;

  EXECUTE format('CREATE INDEX links_geom_idx ON %I.links USING GIST (geom)', schema_name);
  EXECUTE format('ALTER TABLE %I.links ADD PRIMARY KEY (id)', schema_name);
END
\$\$;
EOF
