#!/bin/bash

set -e

cd "$(dirname "$0")/.."

echo "Starting postgres"

PG_IMAGE="postgres@sha256:b7662e5572febc3380fd5773fa600824f0433b82935e7e5b4c180e9541b2b3d7"

docker stop postgres-sqlx || true
CONTAINER_ID=$(docker run --platform linux/amd64 --rm -d --name postgres-sqlx -p 5555:5432 -e POSTGRES_HOST_AUTH_METHOD=trust $PG_IMAGE)

echo "Waiting for postgres to start ${CONTAINER_ID}"

CONTAINER_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $CONTAINER_ID)

echo "Postgres IP: ${CONTAINER_IP}"

export DATABASE_URL=postgres://postgres@localhost:5555

echo "Waiting for postgres to become ready"
for i in {1..30}; do
    if docker run --platform linux/amd64 --network host -e POSTGRES_HOST_AUTH_METHOD=trust $PG_IMAGE psql "${DATABASE_URL}" -c 'SELECT 1;' > /dev/null 2>&1; then
        echo "Postgres is ready"
        break
    fi

    if [ $i -eq 30 ]; then
        echo "Timed out waiting for postgres to start"
        exit 1
    fi

    sleep 0.5
done

# if cargo sqlx doesn't exist, install it
if ! command -v cargo-sqlx &> /dev/null
then
    cargo install sqlx-cli --no-default-features --features postgres
fi

cargo sqlx migrate run --database-url ${DATABASE_URL} --source schema/migrations

{
    echo "-- *****************************************************************"
    echo "-- This file is auto-generated by prepare.sh from migrations/*.sql."
    echo "-- Use it as a reference, but do not modify it directly."
    echo "-- *****************************************************************"
    echo
    echo
} > schema/derived_schema.sql

docker run \
    --platform linux/amd64 \
    --network host \
    -e POSTGRES_HOST_AUTH_METHOD=trust \
    $PG_IMAGE \
    pg_dump -s "${DATABASE_URL}" >> schema/derived_schema.sql

cargo sqlx prepare

docker stop $CONTAINER_ID
