#!/bin/bash

RESTORE_DUMP_GZ=2023-09-06_aactdb_with_matches.sql.gz
POSTGRES_USER=root
POSTGRES_PASSWORD=root
POSTGRES_DB=aact_db

CONTAINER_NAME="${POSTGRES_DB}-restored-$(date -I)"

#start container
podman run \
    -e POSTGRES_PASSWORD="${POSTGRES_PASSWORD}" \
    -e POSTGRES_USER="${POSTGRES_USER}" \
    -e POSTGRES_DB="${POSTGRES_DB}" \
    --name "${CONTAINER_NAME}" \
    --detach \
    --network research-network \
    --shm-size=512mb \
    --volume ./backup/:/backup/ \
    -p 5432:5432\
    postgres:14-alpine


sleep 10

# Function to check if PostgreSQL is ready
function check_postgres {
    podman exec -i "${CONTAINER_NAME}" psql -h "${CONTAINER_NAME}" -U "${POSTGRES_USER}" -d "${POSTGRES_DB}" -c '\q' > /dev/null 2>&1    
}

# Wait for PostgreSQL to be ready
until check_postgres; do
  echo "Waiting for PostgreSQL to be ready..."
  sleep 4
done

echo "PostgreSQL is ready. Restoring the database..."

# Decompress the dump file and restore it to the database
podman exec -i "${POSTGRES_DB}" sh -c "gunzip -c /backup/${RESTORE_DUMP_GZ} | psql -h localhost -U ${POSTGRES_USER} -d ${POSTGRES_DB}"

echo "Database restoration complete."
