#!/bin/sh
#/ 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
cd $(dirname "$0")/../..
. share/github-backup-utils/ghe-backup-config

# 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" -- "[ -d '$GHE_REMOTE_DATA_USER_DIR/$dirname' ]" || exit 0

# If we have a previous increment, avoid transferring existing files via rsync's
# --link-dest support. This also decreases physical space usage considerably.
if [ -d "$GHE_DATA_DIR/current/$dirname" ]; then
    link_dest="--link-dest=../../current/$dirname"
fi

# 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
