#! /bin/bash

set -e
. test/pg-test-lib.sh
ADMIN_PASSWORD=redhat

test $# -eq 2 || error "two args expected: $0 FROM TO"

cleanup()
{
    set +e
    set -- $container_from $container_to
    if test $# -gt 0; then
        docker stop "$@" >/dev/null
        docker rm -f "$@"
    fi
}
trap cleanup EXIT

from=$1
to=$2
image_from=$(get_image_id "$from")
image_to=$(get_image_id "$to")

assert_migration_succeeds ()
{
    info "starting PostgreSQL server v$from"
    container_from=$(docker run -e POSTGRESQL_ADMIN_PASSWORD="$ADMIN_PASSWORD" -d "$image_from")
    wait_for_postgres "$container_from"

    eval "CID=\$container_from data_${1}_create"
    eval "CID=\$container_from data_${1}_check"

    ip=$(container_ip "$container_from")

    info "starting new PostgreSQL server v$to with migration options"
    container_to=$(docker run \
        -e POSTGRESQL_MIGRATION_REMOTE_HOST="$ip" \
        -e POSTGRESQL_MIGRATION_ADMIN_PASSWORD="$ADMIN_PASSWORD" \
        -d "$image_to")

    # Prolong a waiting time here a bit since both dump and restore is done in
    # uncertain environment (usually both is done on the same hardware).
    wait_for_postgres "$container_to" 100

    info "check that the migration passed"
    eval "CID=\$container_to data_${1}_check"

    docker stop "$container_from"
    docker rm -f "$container_from"
    docker stop "$container_to"
    docker rm -f "$container_to"
    container_from= container_to=
}

assert_migration_succeeds pagila
