#!/bin/bash

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

source /root/telegram.env

alias updl="`# rup &&` apt update -q && apt full-upgrade --download-only -y -qq && apt autoremove -y -qq"
#TODO: reinstate restic
alias rup="restic -q -r local:/root/jc/restic/"$HOSTNAME" -p /root/jc/restic/passwd backup /etc ~/.bash_history && restic -q -r local:/root/jc/restic/"$HOSTNAME" -p /root/jc/restic/passwd forget --prune --keep-last 14 --keep-within 3m --keep-weekly 520"
#TODO: restic -p ~/jc/restic/passwd -r local:"??no more nas??/restic/$HOSTNAME" init

function waitNoRunning {
echo '- - - - - - - - Waiting VMs to migrate or shutdown 200s - - - - - - - -'
while true; do
	if /root/admin_scripts/confirm_norunning.sh "$@" >/dev/null; then
		return
	fi

	sleep 3
	printf .
done
}
export -f waitNoRunning

function upg {
	if ! /root/admin_scripts/shutdown_nomigrates.sh; then
		tgmsg 'ERROR: upg: signaling nomigrate shutdowns'
		return 1
	fi

	if ! timeout 200 bash -c waitNoRunning 0; then
		tgmsg 'ERROR: upg: running VMs before upgrade'
		return 1
	fi

	if ! apt full-upgrade -y; then
		tgmsg 'ERROR: upg: upgrade'
		return 1
	fi
}

function upgr {
	# shellcheck disable=SC2119
	off || return $?
	upg || return $?

	# double confirmation
	if ! timeout 200 bash -c waitNoRunning 1; then
		tgmsg 'ERROR: upgr: running VMs before reboot'
		return 1
	fi

	reboot
}

function _off {
	ha-manager crm-command node-maintenance enable "$1" && \
	echo "$1": maintenance mode
}

# shellcheck disable=SC2120
function off {
	if [[ "$#" -gt 0 ]]; then
		_off "$@"
		return "$?"
	else
		_off "$HOSTNAME"
	fi

	roff

	updl
}

function roff {
	/root/admin_scripts/affinity_maintenance.sh 1
	echo 'resource affinities: disabled'
}

function ron {
	/root/admin_scripts/affinity_maintenance.sh 0
	echo 'resource affinities: enabled'
}

function _on {
	ha-manager crm-command node-maintenance disable "$1" && \
	echo "$1": normal mode
}

# shellcheck disable=SC2120
function on {
	if [[ "$#" -gt 0 ]]; then
		_on "$@"
		return "$?"
	else
		_on "$HOSTNAME"
	fi

	echo 're-enable resource affinities: ron'
}

alias h="echo 'avail cmds: off on roff ron | upg upgr | updl localprogress'"

function localprogress () {
	watch ls -lh "/var/lib/vz/images/$1"
}
