#! /bin/bash --

set -e
DOVE="$(mktemp)"

cd "$(dirname "$0")"
pushd production
    source .env && \
    PGPASSWORD="$DB_PASSWORD" \
        pg_dump \
        -h localhost \
        -p "${DB_PORT:-5432}" \
        -U "${DB_USER:postgres}" \
        -c -Fc -Z0  "$DB_NAME" > "$DOVE"
popd
pushd staging
    source .env && \
    echo 'DROP DATABASE "'"$DB_NAME"'";' | \
        psql \
        -h localhost \
        -p "${DB_PORT:-5432}" \
        -U "${DB_USER:postgres}"
    pg_restore \
        -h localhost \
        -p "${DB_PORT:-5432}" \
        -U "${DB_USER:postgres}" \
        -d "$DB_NAME" \
        --clean -Fc \
        -j $(cat /proc/cpuinfo | grep processor | wc -l) "$DOVE"
popd
rm -rf "$DOVE"
docker-compose -f ./staging/docker-compose.yml up -dt1
