#!/bin/bash

# this is far from a perfect estimate, but it's usually pretty decent

set -eu
set -o pipefail

host=""
mount_point=''
do_ssh_copy_id=True

function usage
{
    retval="$1"
	case "$retval" in
		0)
			;;
		*)
			exec 1>&2
			;;
	esac

	echo "Usage: $0"
	echo "    --host                The host to log into to transfer the filesystem from. Can also be of the form username@host"
	echo "    --mount-point         A single directory that is a mount point"
	echo "    --skip-ssh-copy-id    Don't (re)run the ssh-copy-id command"
	echo "    --help                This stuff"
	echo
	echo "Tar up a remote filesystem and pipe it through gprog, using remote df to get an estimate of how much data will need to"
    echo "be copied."
    echo
	echo "Please note that this script will ssh-copy-id, so it has the side effect of setting up passwordless ssh."

    exit "$retval"
}

while [ "$#" -ge 1 ]
do
    if [ "$1" = --host ]
    then
        host="$2"
		shift
    elif [ "$1" = --skip-ssh-copy-id ]
    then
        do_ssh_copy_id=False
    elif [ "$1" = --mount-point ]
    then
        mount_point="$2"
		shift
    elif [ "$1" = --help ] || [ "$1" = "-h" ]
    then
        usage 0
    else
        echo "$0: Illegal option: $1" 1>&2
        usage 1
    fi
    shift
done

all_good=True

case "$host" in
	"")
		echo "$0: --host is a required option" 1>&2
		all_good=False
		;;
esac

tab=$(printf '\t')
case "$mount_point" in
	"")
		echo "$0: --mount-point is a required option" 1>&2
		all_good=False
		;;
	*" "*|*"$tab"*)
		echo "$0: I do not work with mountpoints that contain whitespace" 1>&2
		all_good=False
		;;
esac

case "$all_good" in
	True)
		;;
	False)
		echo "$0: one or more items in the preflight check failed. Please try again" 1>&2
		usage 1
		;;
	*)
		echo "$0: internal error: \$all_good is neither True nor False" 1>&2
		exit 1
		;;
esac

case "$do_ssh_copy_id" in
	True)
		ssh-copy-id "$host"
		;;
	False)
		;;
	*)
		echo "$0: internal error: \$do_ssh_copy_id neither True nor False" 1>&2
		exit 1
		;;
esac

tar=$(ssh "$host" 'PATH="$PATH":/usr/local/bin type -path gtar || type -path tar')

# shellcheck disable=SC2029
df_output=$(ssh "$host" "df -k \"$mount_point\"")

estimate=$(set -eu; echo "$df_output" | get-disk-free --mount-point "$mount_point")

echo "Estimate: $estimate bytes" 1>&2

# shellcheck disable=SC2029
ssh "$host" "cd \"$mount_point\" && \"$tar\" --create --sparse --one-file-system ." \
	| gprog --size-estimate "$estimate" --title "gprog-df-tar $mount_point"