#!/usr/bin/env bash
#/ Usage: ghe-backup-redis
#/ 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
# shellcheck source=share/github-backup-utils/ghe-backup-config
. "$( 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.
ghe-ssh "$GHE_HOSTNAME" /bin/bash <<EOF
  set -e

  if which ghe-redis-cli > /dev/null; then
    redis_cli=ghe-redis-cli
    redis_arg=--remote
  else
    redis_cli=redis-cli
    redis_arg=
  fi
  redis_host=\$(ghe-config cluster.redis-master 2>/dev/null || echo "localhost")
  timestamp=\$(\$redis_cli \$redis_arg -h \$redis_host LASTSAVE)

  for i in \$(seq 10); do
    if ! \$redis_cli \$redis_arg -h \$redis_host BGSAVE | grep -q ERR; then
      break
    fi
    sleep 15
  done
  for n in \$(seq 3600); do
    if [ "\$(\$redis_cli \$redis_arg -h \$redis_host LASTSAVE)" != "\$timestamp" ]; then
      break
    fi
    sleep 1
  done
  [ "\$(\$redis_cli \$redis_arg -h \$redis_host LASTSAVE)" != "\$timestamp" ] # exits 1 if bgsave didn't work

  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)"
