#!/bin/bash

output_cmd_to () {
	path="$1" ; shift
	temp="$(mktemp --tmpdir "$(printf '%s' "$path" | sed "s_$HOME/*__" | tr --complement '[:alnum:]_.' _ )".tmp.XXXXXXXXXXXXXX)"
	if "$@" > "$temp" && [ -s "$temp" ] && ! cmp --silent "$path" "$temp" ; then
		mv --force "$temp" "$path"
	else
		rm --force "$temp"
	fi
}

for host ; do
	A=A
	X=X
	case "$host" in
		*.onion)
			# rsync over tor onion is too slow
			continue
		;;
		f[ia]*.debian.org)
			X=
		;;
		exodar.debian.net)
			A=
			X=
		;;
		lemon.debian.net)
			X=
		;;
		rouster.local)
			A=
		;;
		bonedaddy.net)
			rsync -aSH"$A$X" --delete bonedaddy.net:/var/www/bonedaddy/pabs3/ ~/backup/hosts/bonedaddy.net-www/
		;;
		shell.sourceforge.net)
			# FIXME: run this and kill it later
			#ssh pabs3,icns@shell.sourceforge.net -tt create
		;;
	esac

	# FIXME: workaround something broken in ssh-agent and rsync
	ssh "$host" true

	if [ -s ~/backup/excludes/"$host" ] ; then
		rsync -aSH"$A$X" --delete --delete-excluded --exclude-from ~/backup/excludes/"$host" "$host": ~/backup/hosts/"$host"/
	else
		rsync -aSH"$A$X" --delete --delete-excluded "$host": ~/backup/hosts/"$host"/
	fi

	case "$host" in
		shell.sourceforge.net|pr.pico.sh)
			cron=0
			at=0
			mail=0
		;;
		bonedaddy.net)
			cron=0
			at=0
			mail=0
		;;
		debconf4.dh.bytemark.co.uk)
			cron=0
			at=0
			mail=0
		;;
		*.debian.org)
			cron=1
			at=1
			mail=0
		;;
		*)
			cron=1
			at=1
			mail=1
		;;
	esac

	if [ $cron -eq 1 ] ; then
		output_cmd_to ~/backup/hosts/crontab/"$host" ssh "$host" crontab -l
	fi

	if [ $at -eq 1 ] ; then
		output_cmd_to ~/backup/hosts/at/"$host" ssh "$host" 'atq | cut -f1 | xargs -r at -c | grep -vE "^(SYSTEMD_EXEC_PID|SESSION_MANAGER|GNOME_TERMINAL_SCREEN|GNOME_TERMINAL_SERVICE|XAUTHORITY|MALLOC_PERTURB_|VTE_VERSION|SSH_CONNECTION|SSH_CLIENT|XDG_SESSION_ID)="'
	fi

	if [ $mail -eq 1 ] ; then
		rsync -aSH"$A$X" --delete --delete-excluded "$host:/var/mail/*pabs*" ~/backup/hosts/mail/"$host"/
	fi
done
wait
find ~/backup/hosts/crontab/ -mindepth 1 -empty -delete
find ~/backup/hosts/at/ -mindepth 1 -empty -delete
find ~/backup/hosts/mail/ -mindepth 1 -empty -delete
git -C ~/backup/hosts/crontab/ commit --all --quiet "--message=Import $(date --rfc-3339 second)" > /dev/null || true
git -C ~/backup/hosts/at/ commit --all --quiet "--message=Import $(date --rfc-3339 second)" > /dev/null || true
