#!/usr/local/bin/bash
#/ Usage: ghe-backup-redis-cluster
#/ Take a snapshot of all Redis data. This is needed because older versions of
#/ the remote side ghe-export-redis command use a blocking SAVE instead of a
#/ non-blocking BGSAVE.
#/
#/ Note: This script typically isn't called directly. It's invoked by the
#/ ghe-backup command.
set -e

# Bring in the backup configuration
. $( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config

bm_start "$(basename $0)"

# Perform a host-check and establish GHE_REMOTE_XXX variables.
ghe_remote_version_required "$GHE_HOSTNAME"

# Force a redis BGSAVE, and wait for it to complete.
sudo=
[ "$GHE_VERSION_MAJOR" -ge 2 ] && sudo="sudo"
ghe-ssh "$GHE_HOSTNAME" /bin/sh <<EOF
    set -e

    redis_host=\$(ghe-config cluster.redis-master 2>/dev/null || echo "localhost")
    timestamp=\$(redis-cli -h \$redis_host LASTSAVE)
    redis-cli -h \$redis_host BGSAVE 1>/dev/null

    while [ \$(redis-cli -h \$redis_host LASTSAVE) -eq \$timestamp ]; do
        sleep 1
    done

    if [ "\$redis_host" != "localhost" ]; then
      ssh \$redis_host $sudo cat '$GHE_REMOTE_DATA_USER_DIR/redis/dump.rdb'
    else
      $sudo cat '$GHE_REMOTE_DATA_USER_DIR/redis/dump.rdb'
    fi
EOF

bm_end "$(basename $0)"
