#! /bin/bash --
set -e
set -o pipefail
cd "$(dirname "$0")"

FROM="production"
TO="none (export only)"
EXIT_STATUS_ON_NO_TARGET=0
SERVICE="sangue"

print_usage() {
    echo "copydb.sh [options]

    Copy db.

    Options:
     -f, --from             source deployment name [default: $FROM]
     -t, --to               destination deployment name [default: $TO]
     -s, --service          service name [default: $SERVICE]
     -h, --help             show this help

    "
}


set +e
TEMP=$(getopt -o f:t:s:h --long from:,to:,service:,help -- "$@")
GETOPT_STATUS=$?
set -e

if [[ ! $GETOPT_STATUS = 0 ]]; then
    print_usage
    exit 1
fi
eval set -- "$TEMP"

while true; do
	case "$1" in
		-f|--from)
			FROM="$2"
			shift 2
			;;
		-t|--to)
			EXIT_STATUS_ON_NO_TARGET=6
			TO="$2"
			shift 2
			;;
		-s|--service)
			SERVICE="$2"
			shift 2
			;;
        -h|--help)
            print_usage
            exit 1
            ;;
		--)
			shift
			break
			;;
		*)
			echo "Internal error!" 1>&2
			exit 1
			;;
	esac
done
OUTNAME="/tmp/$SERVICE-$FROM-$(date '+%s')-XXXXXX.dump.zstd"
OUTFILE="$(mktemp $OUTNAME)"

echo -e "from deployment:\t$FROM\nto deployment:\t$TO\ncompose service:\t$SERVICE\ntemporary file:\t$OUTFILE" | column -t -s "$(printf '\t')"
read -p "Are you sure? (y/n) " -n 1 -r CONFIRM
echo #a capo

if [[ ! $CONFIRM =~ ^[Yy]$ ]]; then
	exit 3;
fi



COMANDO_EXPORT='set -e; set -o pipefail; env PGPASSWORD="$DB_PASSWORD" pg_dump -h ${DB_HOST:-localhost} -p "${DB_PORT:-5432}" -U "${DB_USER:-postgres}" -c -Fc -Z0 "$DB_NAME"'
B64_EXPORT=$(echo "$COMANDO_EXPORT" | base64)
COMANDO_DROP='set -e; set -o pipefail; echo "DROP DATABASE IF EXISTS \"$DB_NAME\"; CREATE DATABASE \"$DB_NAME\" WITH OWNER=\"$DB_USER\"; " | env PGPASSWORD="$DB_PASSWORD" psql -v ON_ERROR_STOP=1 -h ${DB_HOST:-localhost} -p "${DB_PORT:-5432}" -U "${DB_USER:-postgres}" postgres'
COMANDO_IMPORT='set -e; set -o pipefail; env PGPASSWORD="$DB_PASSWORD" pg_restore --no-owner -h ${DB_HOST:-localhost} -p "${DB_PORT:-5432}" -U "${DB_USER:postgres}" -d "$DB_NAME" -Fc'
B64_IMPORT=$(echo "$COMANDO_IMPORT" | base64)

echo "Exporting from $FROM..."
echo "$B64_EXPORT" | (cd "$FROM" && docker-compose exec -T "$SERVICE" "/bin/bash" -c 'base64 -d | bash' | zstd )> "$OUTFILE"
echo "Export from $FROM OK"
if [[ ! -f "./$TO/docker-compose.yml" ]]; then
	if [[ ! $EXIT_STATUS_ON_NO_TARGET = 0 ]]; then
		echo "No target specified or found"
	fi
	exit $EXIT_STATUS_ON_NO_TARGET
fi

MUST_RESTART=0
IS_RUNNING=$(cd "$TO" && docker-compose ps -q "$SERVICE" | wc -l)
if [[ $IS_RUNNING != "0" ]]; then
    MUST_RESTART=1
    echo -n "Stop $SERVICE in $TO... "
    (cd "$TO" && docker-compose stop -t3 "$SERVICE")
    echo "stopped."
else
    echo "$TO is already stopped."
fi

echo "Drop old/create new database in $TO..."
DROP_OUTPUT=$(cd "$TO" && docker-compose run --rm -T "$SERVICE" "/bin/bash" -c "$COMANDO_DROP")
echo "Drop/create database in $TO OK"

echo "Importing into $TO..."
zstdcat "$OUTFILE" | (cd "$TO" && docker-compose run --rm -T "$SERVICE" "/bin/bash" -c "$COMANDO_IMPORT")
echo "Import into $TO OK"
if [[ $MUST_RESTART = "1" ]]; then
    echo -n "Starting $TO... "
    (cd "$TO" && docker-compose up -d)
    echo "started."
fi
exit 0
