#!/usr/bin/env bash
#/ Usage: ghe-backup-userdata <dirname>
#/ Take an online, incremental snapshot of a user data directory. This is used
#/ for a number of different simple datastores kept under /data/user on the
#/ remote appliance, including: hookshot, alambic_assets, and pages data.
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) - $1"

# Verify rsync is available.
if ! rsync --version 1>/dev/null 2>&1; then
  echo "Error: rsync not found." 1>&2
  exit 1
fi

# Grab the host and /data/user directory name.
host="$GHE_HOSTNAME"
dirname="$1"

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

# Verify that the user data directory exists. Bail out if not, which may be due
# to an older version of GHE or no data has been added to this directory yet.
ghe-ssh "$host" -- "sudo -u git [ -d '$GHE_REMOTE_DATA_USER_DIR/$dirname' ]" || exit 0

# If we have a previous increment and it is not empty, avoid transferring existing files via rsync's
# --link-dest support. This also decreases physical space usage considerably.
if [ -d "$GHE_DATA_DIR/current/$dirname" ] && [ "$(ls -A $GHE_DATA_DIR/current/$dirname)" ]; then

  subdir=$dirname
  link_path=".."
  while true; do
    if [ "$(dirname $subdir)" = "." ]; then
      break
    fi

    if [ "$(dirname $subdir)" = "/" ]; then
      break
    fi

    link_path="../$link_path"
    subdir=$(dirname $subdir)
  done

  link_dest="--link-dest=../${link_path}/current/$dirname"
fi

# Ensure target directory exists, is needed with subdirectories
mkdir -p "$GHE_SNAPSHOT_DIR/$dirname"

# Transfer all data from the user data directory using rsync.
ghe-rsync -avz \
  -e "ghe-ssh -p $(ssh_port_part "$host")" \
  --rsync-path='sudo -u git rsync' \
  $link_dest \
  "$(ssh_host_part "$host"):$GHE_REMOTE_DATA_USER_DIR/$dirname/" \
  "$GHE_SNAPSHOT_DIR/$dirname" 1>&3

bm_end "$(basename $0) - $1"
