#!/bin/sh
set -eu

echo "Waiting for Debezium replication slot..."

until [ "$(psql -Atc "select coalesce((select active from pg_replication_slots where slot_name = 'debezium'), false);")" = "t" ]; do
  sleep 1
done

echo "Creating inventory CDC events..."

psql <<'SQL'
truncate table inventory restart identity;

insert into inventory (sku, name, quantity, location)
values
  ('FL-100', 'Archive label rolls', 12, 'Torshavn'),
  ('FL-220', 'Scanner cleaning kit', 7, 'Klaksvik'),
  ('FL-330', 'Cold storage boxes', 18, 'Runavik');

update inventory set quantity = quantity - 1, updated_at = now() where sku = 'FL-100';
update inventory set quantity = quantity + 5, updated_at = now() where sku = 'FL-220';
update inventory set location = 'Suduroy', updated_at = now() where sku = 'FL-330';
delete from inventory where sku = 'FL-220';
SQL

echo "Done."
