#!/bin/bash
#
# ::copy1::
# ::copy2::
#
CMD=$(basename "$0")
CMDVER="1.10"
CMDSTR="$CMD v$CMDVER (2024-09-25)"

set -e -u


usage()
{
	echo "
== $CMDSTR == watch current backup infos ==

usage: $CMD [-lines] [interval]

options:
  . a positive number is used as refresh interval, in seconds
    default is $interval sec
  . a negative number -N is used to display last N lines of
    current backup logfile, default is $lines

NOTE: overall stats (Gb copied, elapsed time) are referred to
the launch of this program, not to the backup start; real stats
are computed at end of backup, sent via email and saved in
kubackup workdir files 'last-report*.txt'
" >&2
	exit 1
}


# (MAIN)

interval='2'
lines='-6'

while [ $# != 0 ]
do
	case ${1:-} in
	  "")		;;
	  [1-9]*)	interval=$1 ;;
	  -[0-9]*)	lines=$1 ;;
	  *)		usage ;;
	esac
	shift
done

# get current cmdline config
#
lastrun=$(grep ' STARTED ' /var/log/kubackup-run | tail -1)
case $lastrun in
 *" -c "*|*" --config "*)
 	cfg=$(echo "$lastrun" | sed -e 's/.* -c //' -e 's/ --config //' -e 's/ .*//')
	cfg="--config $cfg"
	;;
 *)
 	cfg=""
esac


# bckdir is needed to get the space usage/free on backup disk
# this path is passed to child process, too
#
[ -r /var/log/kubackup-run ] || {
	echo -e "\n$CMD ERROR: /var/log/kubackup-run not exists or not readable\n" >&2
	exit 1
}
bckdir=$(fgrep ' backup dir ' /var/log/kubackup-run | tail -1 \
	| sed -e 's/.* backup dir //' -e 's/ .*//' -e 's/,.*//')

# resets stats flagfiles, used by child cmd
#
du=$(df -m $bckdir | tail -1); set -- $du; du=$3
echo "$du" >/tmp/$CMD-start
echo "$du" >/tmp/$CMD-prev

# get current workdir
#
workdir=$(kubackup-getconf $cfg 'workdir')

cd "$workdir"
exec watch --interval $interval ${CMD}-cmd $bckdir $lines
