#! /bin/bash --

# REQUISITI:
# sul server E sul client ci deve essere installato:
#  - pgdump versione corretta
#  - zstd
#  - base64
#  - ssh server

set -e
DOVE="$(mktemp)"

cd "$(dirname "$0")/.." && source .env
COMANDO='set -e; cd "'"$2"'" && source env_docker && PGPASSWORD="$DB_PASSWORD" pg_dump -h localhost -p "${DB_PORT:-5432}" -U "${DB_USER:postgres}" -c -Fc -Z0  "$DB_NAME" | zstd'
B64=$(echo "$COMANDO" | base64)
ssh "$1" "echo '$B64' | base64 -d | bash" | zstdcat > "$DOVE"
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"
rm -rf "$DOVE"
