#!/bin/bash

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

set -eu
set -o pipefail

mount_point=''

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

	echo "Usage: $0"
	echo "    --mount-point         A single directory that is a mount point"
	echo "    --help                This stuff"
	echo
	echo "Tar up a local filesystem and pipe it through gprog, using df to get an estimate of how much data will need to be copied."

    exit "$retval"
}

while [ "$#" -ge 1 ]
do
    if [ "$1" = --mount-point ]
    then
        mount_point="$2"
		shift
    elif [ "$1" = --help ]
    then
        usage 0
    else
        echo "$0: Illegal option: $1" 1>&2
        usage 1
    fi
    shift
done

if type -path gtar > /dev/null 2>&1
then
	tar=gtar
else
	tar=tar
fi

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

df_output=$(df -k "$mount_point")

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

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

cd "$mount_point"

"$tar" --create --sparse --one-file-system . | gprog --size-estimate "$estimate" --title "gprog-df-tar $mount_point"