#!/bin/sh

. /etc/control.d/functions

INCLUDE_CFG=/etc/sisyphus-mirror/include

new_summary 'sisyphus-mirror include file: mirroring src.rpm packages'

new_help mirror 'mirror src.rpm packages is ON'
new_help nomirror 'mirror src.rpm packages is OFF'

PAT_DIR='SRPMS\*/$'
PAT_FILES='SRPMS/\*\*$'
PAT_DIR_COM="^#$PAT_DIR"
PAT_FILES_COM="^#$PAT_FILES"

check_dir()
{
	grep -qn1 "^$PAT_DIR" -- "$INCLUDE_CFG"
}

check_files()
{
	grep -qn1 "^$PAT_FILES" -- "$INCLUDE_CFG"
}

get_status()
{
	local STATUS=unknown
	if check_dir; then
		if check_files; then
			STATUS=mirror
		fi
	elif ! check_files; then
		STATUS=nomirror
	fi
	echo "$STATUS"
}

un_com()
{
	# $1 - PAT_*_COM
	local PAT_COM="$1"
	sed -i --follow-symlinks -e "\\@$PAT_COM@ {s@^#@@; : loop; n; b loop}" -- "$INCLUDE_CFG" || return 1
}

to_com()
{
	# $1 - PAT_*
	local PAT="$1"
	sed -i --follow-symlinks -e "\\@^$PAT@ s@^@#@" -- "$INCLUDE_CFG" || return 1
}

REQUEST="$*"

case "$REQUEST" in
	help|'help '*)
		control_help "${REQUEST#help}"
		;;
	list)
		control_list
		;;
	summary)
		control_summary
		;;
	status|'')
		get_status
		;;
	mirror|nomirror)
		CURRENT="$(get_status)"
		if [ "$REQUEST" != "$CURRENT" ]; then
			case "$REQUEST" in
				mirror)
					if [ ! -s "$INCLUDE_CFG" ]; then
						printf '%s\n%s\n' 'SRPMS*/' 'SRPMS/**' > "$INCLUDE_CFG" || exit 1
					else
						if ! check_files; then
							if grep -qn1 "$PAT_FILES_COM" -- "$INCLUDE_CFG"; then
								un_com "$PAT_FILES_COM" || exit 1
							else
								sed -i --follow-symlinks -e '1 iSRPMS/**' -- "$INCLUDE_CFG" || exit 1
							fi
						fi
						if ! check_dir; then
							if grep -qn1 "$PAT_DIR_COM" -- "$INCLUDE_CFG"; then
								un_com "$PAT_DIR_COM" || exit 1
							else
								sed -i --follow-symlinks -e '1 iSRPMS*/' -- "$INCLUDE_CFG" || exit 1
							fi
						fi
					fi
					;;
				nomirror)
					if [ ! -e "$INCLUDE_CFG" ]; then
						: > "$INCLUDE_CFG" || exit 1
					else
						if check_dir; then
							to_com "$PAT_DIR" || exit 1
						fi
						if check_files; then
							to_com "$PAT_FILES" || exit 1
						fi
					fi
					;;
			esac
		fi
		;;
	*)
		printf '%s: %s\n' "${0##*/}" "Invalid mode: $REQUEST" >&2
		exit 1
esac
