#!/usr/bin/env bash

set -euo pipefail

./tools/get_database_size.sh
output="./tools/db.sql"
schema_output="./tools/schema.sql"

./tools/dump_database.sh &> ${output}
./tools/dump_schema.sh &> ${schema_output}

container_name="${CONTAINER_NAME:-"health_api_postgres_1"}"
echo "Working with container name ${container_name}. Override the CONTAINER_NAME variable to select a different container"
docker exec -i "${container_name}" psql -U postgres -c "CREATE ROLE srv_redshift" || echo "create role failed, already exists?"

# TODO - reduce errors
# example error:
# pg_restore: from TOC entry 2970; 2606 12428824 FK CONSTRAINT platform platform_updated_by_id_fkey health_api
# pg_restore: error: could not execute query: ERROR:  constraint "platform_updated_by_id_fkey" for relation "platform" already exists
# Command was: ALTER TABLE ONLY public.platform
#     ADD CONSTRAINT platform_updated_by_id_fkey FOREIGN KEY (updated_by_id) REFERENCES public.token(id);
echo "creating schema"
docker exec -i "${container_name}" pg_restore -d health_api -U health_api  -s < ${schema_output} || echo "
----------------------------------------------------
Errors while creating schema
----------------------------------------------------"
echo "inserting data"

# TODO - reduce errors
# example error:
#   pg_restore: from TOC entry 3103; 0 12428852 TABLE DATA platform_note health_api
#   pg_restore: error: could not execute query: ERROR:  permission denied: "RI_ConstraintTrigger_c_16475" is a system trigger
#   Command was: ALTER TABLE public.platform_note DISABLE TRIGGER ALL;
docker exec -i "${container_name}" pg_restore -d health_api -U health_api --disable-triggers < ${output} || echo "
----------------------------------------------------
Errors while inserting data. Some or all of the data
may have successfully inserted
----------------------------------------------------"
