#!/bin/bash
#
# ::do_not_edit::
# ::maintainer::
#
CMD=$(basename $0)
CMDVER="1.0"
CMDSTR="$CMV v$CMVVER (2026-08-01)"

set -e -u

LOGFILE="/var/log/veeam-agent.log"

usage()
{
	echo "
usage: $CMD {-n|-x} [options] [jobname [veeam-agent-options]]

options:
  -n|--dry-run	show only commands
  -x|--execute	runs commands (note, -x or -n are mandatory)

  -v|--verbose	be verbose, duplicate log messages to stdout,
  		note that all output will go to logfile
		($LOGFILE)

" >&2
	[ $# != 0 ] && echo -e "\n$*\n" >&2
	exit 1
}

# (MAIN)

. /lib/ku-base/log.sh

VERBOSE=false
F_EXEC=
dummy=
job_name=$(kusa-conf veeam-agent.job_name)

export PATH="$PATH:/sbin:/usr/sbin"

[ $# = 0 ] && usage

while [ $# != 0 ]
do
  case $1 in
    -v|--verbose)	VERBOSE=true ;;
    -n|--dry-run)	F_EXEC=false ;;
    -x|--exec*)		F_EXEC=true ;;
    -*)			usage ;;
    *)			break ;;
  esac
  shift
done

[ "$F_EXEC" = "" ] && usage "you must use '-n' or '-x'"
[ $# != 0 ] && {
	job_name=$1
	shift
}
$F_EXEC || dummy="(dummy) "


# rotate logfile if needed
ku_cap_logfile

# not verbose, capture all output to logfile
$VERBOSE || exec 2>&1 >>$LOGFILE

cmd="veeamconfig job start --name $job_name"

ku_log "STARTED"
ku_log "RUN $dummy$cmd $*"

retstat=0

$F_EXEC && {
	$cmd "$@" || retstat=$?
}

ku_log "ENDED status=$retstat"
exit $retstat
