# NOTE: if you run this Makefile on the VM, you want to run it as the
# chef-pgsql user (sudo -iu chef-pgsql)

TEST_DB ?= delivery_test

# If your database dump isn't installing properly, it probably means
# you've got some new migrations that need to be applied to the data
# in the dump. If that's the case, try setting this variable to the
# most recent tag instead.
#
# If that fixed it, then once your change is accepted, submit a new
# change with an updated dump by running `make update_dump` and then
# change this back to `@HEAD`. If you try and do that as you're coding
# your change, you'll likely run into too much friction.
#
# However, if you run into issues with test data in $(DATA_FILE), make
# those changes directly in that file; that gets added to the database
# after all schema has been deployed.
DUMP_INSTALLS_AT_VERSION = @HEAD

# See the load_data target
DATA_DUMP = t/sanitized_shd.dump
DATA_FILE = t/delivery_test_data.sql

HELPER   = t/delivery_pgtap_functions.sql
STARTUP  = $(wildcard t/startup_*.sql)
SETUP    = $(wildcard t/setup_*.sql)
TEARDOWN = $(wildcard t/teardown_*.sql)
SHUTDOWN = $(wildcard t/shutdown_*.sql)
TEST     = $(wildcard t/test_*.sql)

ALL_FUNCTIONS = $(HELPER) $(STARTUP) $(SETUP) $(TEARDOWN) $(SHUTDOWN) $(TEST)

# Lists all the pgSQL extensions we use
CORE_EXTENSIONS = uuid-ossp
TEST_EXTENSIONS = pgtap chef_pgtap

all: recreate_database setup_extensions setup_load_data setup_schema load_data test

recreate_database:
	@echo "Dropping and recreating database '$(TEST_DB)'"
	@psql --dbname template1 --single-transaction --command 'DROP DATABASE IF EXISTS $(TEST_DB)'
	@psql --dbname template1 --single-transaction --command 'CREATE DATABASE $(TEST_DB)'

setup_schema:
	-@PGOPTIONS='-c client_min_messages=WARNING' sqitch --verbose --db-name $(TEST_DB) --db-host localhost deploy --verify

setup_extensions: core_extensions test_extensions

core_extensions:
	@$(foreach EXT,$(CORE_EXTENSIONS), psql --dbname $(TEST_DB) --command 'CREATE EXTENSION IF NOT EXISTS "$(EXT)";';)

test_extensions:
	@$(foreach EXT,$(TEST_EXTENSIONS), psql --dbname $(TEST_DB) --command 'CREATE EXTENSION IF NOT EXISTS "$(EXT)";';)

$(ALL_FUNCTIONS):
	@PGOPTIONS='-c client_min_messages=WARNING' psql --dbname $(TEST_DB) --single-transaction --set ON_ERROR_STOP=1 --file $@

# With more complicated views and functions in the database, bringing
# in realistic data for testing is more important. To that end, we've
# included a binary dump file taken from our self-hosted
# deployment. It is "real" except that the phase run logs and status
# fields have been dramatically truncated (saving us orders of
# magnitude in space).
#
# We'll then layer on the manually-created data that we've been using
# for other tests, just so everything doesn't break at once.
setup_load_data:
	@PGOPTIONS='-c client_min_messages=WARNING' sqitch --verbose --db-name $(TEST_DB) --db-host localhost deploy --verify $(DUMP_INSTALLS_AT_VERSION)
	pg_restore --create --dbname=$(TEST_DB) --data-only --disable-triggers --schema=public $(DATA_DUMP)

load_data: $(ALL_FUNCTIONS)
	psql --dbname $(TEST_DB) --set ON_ERROR_STOP=1 --file $(DATA_FILE)

# Create a fresh database, load the schema up to
# DUMP_INSTALLS_AT_VERSION, and then apply the rest of the
# migrations. Useful for when you need to create a new dump with
# migrations applied. Also useful for inserting your own additional
# data, should the mood strike you
setup_new_dump: recreate_database setup_load_data setup_schema

# Use this to create a new database dump file.
create_new_dump:
	# TODO: Until we remove the stage_ordering table altogether, we
	# need to remove its data from the dump, since that data is actually
	# generated by Sqitch
	@psql --dbname ${TEST_DB} --single-transaction --command 'DELETE FROM stage_ordering'
	# Sqitch's metadata registry doesn't need to be in the dump (and
	# would cause issues when restored) so let's not keep it
	@pg_dump --format=custom ${TEST_DB} --file=${DATA_DUMP} --exclude-schema=sqitch

# Convenience target provided for the "normal" use case of creating a
# new dump purely from the existing dump and any new migrations.
updated_dump: setup_new_dump create_new_dump

test: $(ALL_FUNCTIONS)
	@echo "Executing xUnit-style pgTAP tests in database '$(TEST_DB)'"
	@pg_prove --dbname $(TEST_DB) --verbose --runtests

# Useful for testing your revert scripts; just reverts everything
revert:
	@PGOPTIONS='-c client_min_messages=WARNING' sqitch --db-name $(TEST_DB) --db-host localhost revert -y

# Tests all deploy, verify, pgTAP, and revert scripts
round_trip: all revert

# Convenience target for getting into the test database to poke around
psql:
	psql -d $(TEST_DB)

# So, the test function files are actually real files, but we want to
# ensure that they always get installed using their target.
# Previously, we used a foreach loop to execute the psql command, but
# if any of the installations failed (e.g., due to a syntax error in a
# test function), makefile processing still continued, despite the
# fact that psql was returning a non-zero return code.
#
# An alternative would be to use FORCE, as detailed in
# https://www.gnu.org/software/make/manual/html_node/Force-Targets.html.
.PHONY: $(ALL_FUNCTIONS) revert
