#!/bin/sh
# Purpose {{{
## Create a temp file (to monitor) if an upgrade is available for AdGuard Home
## project on Github.
## It's based on the AdGuard Home bin path to get the current version.
## How-to use {{{
### 1. Needs releasetags script, in the same directory
### cf. https://git.101010.fr/gardouille-dotfiles/scripts/github/releasetags
# wget https://git.101010.fr/gardouille-dotfiles/scripts/raw/branch/master/github/releasetags
### 2. Create a cron job with AdGuard Home binary's path as first argument, eg.
#00 20 * * * root /opt/repos/ipr.scripts/github/check_adguard_update --bin /opt/adguard/AdGuardHome/AdGuardHome
### 3. Monitor the temp file : /tmp/.adguard.upgrade
# Or enable MAILTO in cronjob and edit the script to print a message.
# Or send a mail.
# …
## }}}
# }}}

# Vars {{{
readonly PROGNAME=$(basename "${0}")
readonly NBARGS="${#}"
## Test if DEBUG is already defined (by parent script,…)
[ -z "${DEBUG}" ] && DEBUG=1

## Colors
readonly PURPLE='\033[1;35m'
readonly RED='\033[0;31m'
readonly RESET='\033[0m'
readonly COLOR_DEBUG="${PURPLE}"

script_wd=$(dirname "${0}")
adguard_repo_url="https://github.com/AdguardTeam/AdGuardHome"
# }}}

usage() {                                                       # {{{

	cat <<- EOF
usage: $PROGNAME [-b|-d|-f|-h]
Compare current version of an installed AdGuard Home bin and the last available.

EXAMPLE :
    - Compare the current version of AdGuard Home with default bin
        check.adguard.update

    - Specify the path to AdGuardHome binary
        check.adguard.update --bin /home/adguard/AdGuardHome/AdGuardHome

OPTIONS :
    -b,--bin
        Specify the path of AdGuard Home's binary
        (default: /opt/adguard/AdGuardHome/AdGuardHome).

    -f,--file
        Set the path to the temp file that will be create and
        that should be monitored (default: /tmp/.adguard.upgrade).

    -d,--debug
        Enable debug messages.

    -h,--help
        Print this help message.

EOF

}
# }}}
debug_message() {                                               # {{{

	local_debug_message="${1}"

	## Print message if DEBUG is enable (=0)
	[ "${DEBUG}" -eq "0" ] && printf '\e[1;35m%-6b\e[m\n' "DEBUG − ${PROGNAME} : ${local_debug_message}"

	return 0
}
# }}}
error_message() {                                               # {{{

	local_error_message="${1}"
	local_error_code="${2}"

	## Print message if DEBUG is enable (=0)
	[ "${DEBUG}" -eq "0" ] && printf '%b\n' "ERROR − ${PROGNAME} : ${RED}${local_error_message}${RESET}"

	exit "${local_error_code:=66}"
}
# }}}
is_var_empty() {                                                # {{{

	## Return False by default
	return_var_empty="1"
	## Total number of variables to test
	local_total_var="${#}"

	loop_count_var_empty="0"

	## While it remains a variable to test
	while [ "${local_total_var}" -gt "${loop_count_var_empty}" ]; do
		debug_message "is_var_empty − \
Test var: ${1}."
		### Test if this is empty and set return value to True
		[ -z "${1}" ] && return_var_empty="0"

		### Increase the number of tested variables
		loop_count_var_empty=$((loop_count_var_empty+1))

		### Shift to the next variable
		shift
	done

	return "${return_var_empty}"

}
# }}}
define_vars() {                                                 # {{{

	## If adguard_bin wasn't defined (argument,...) {{{
	if [ -z "${adguard_bin}" ]; then
		### Use default value
		adguard_bin="/opt/adguard/AdGuardHome/AdGuardHome"
	fi
	## }}}

	## If adguard_new_version_file wasn't defined (argument,...) {{{
	if [ -z "${adguard_new_version_file}" ]; then
		### Store it in /tmp directory
		adguard_new_version_file="/tmp/.adguard.upgrade"
	fi
	## }}}

	adguard_current_version=$(${adguard_bin} --version | \
		cut --delimiter=" " --field=4 --)

	adguard_new_version=$("${script_wd}"/releasetags "${adguard_repo_url}" | \
		grep --invert-match --extended-regexp -- '(dev|rc|-b.)' | \
		head --lines=1)

}
# }}}

main() {                                                        # {{{

	## Define all vars according to selected options
	define_vars

	## Test adguard_current_version
	##   AND exit with error 2
	is_var_empty "${adguard_current_version}" \
		&& error_message "adguard_current_version seems empty (${adguard_current_version})." 2

	## Test adguard_new_version
	##   AND exit without error
	is_var_empty "${adguard_new_version}" \
		&& debug_message "adguard_new_version seems empty (${adguard_new_version}), exit without error." \
		&& exit 0

	## Check if the current version is the last one {{{
	if [ "${adguard_current_version}" != "${adguard_new_version}" ]; then
		debug_message "Test AdGuard Home version − \
Current version (${adguard_current_version}) and new one (${adguard_new_version}) seems to be different."

		## Create a temp file to monitor
		debug_message "Test AdGuard Home version − \
Create ${adguard_new_version_file} temp file to monitore."
		touch -- "${adguard_new_version_file}"
		printf '\e[1;35m%-6s\e[m\n' "An upgrade is available for AdGuard Home (current : ${adguard_current_version}) : ${adguard_new_version}." >> "${adguard_new_version_file}"

	else
		debug_message "Test AdGuard Home version − \
The current version (${adguard_current_version}) is up-to-date."
		rm --force -- "${adguard_new_version_file}"
	fi
	## }}}

}
# }}}

# Manage arguments                                                # {{{
# This code can't be in a function due to arguments

if [ ! "${NBARGS}" -eq "0" ]; then

	## If the first argument is not an option
	if ! printf -- '%s' "${1}" | grep --quiet --extended-regexp -- "^-+";
	then
		usage
		error_message "Unknown argument (${1}), check the help." 1
	fi

	manage_arg="0"

	# Parse all options (start with a "-") one by one
	while printf -- '%s' "${1}" | grep --quiet --extended-regexp -- "^-+"; do

	case "${1}" in
		-b|--bin )             ## Set binary's path
			## Move to the next argument
			shift
			## Define adguard_bin
			adguard_bin="${1}"
			;;
		-d|--debug )           ## debug
			DEBUG=0
			;;
		-h|--help )            ## help
			usage
			## Exit after help informations
			exit 0
			;;
		-f|--file )            ## Set temp file
			## Move to the next argument
			shift
			## Define adguard_new_version_file
			adguard_new_version_file="${1}"
			;;
		-- )                   ## End of options list
			## End the while loop
			break
			;;
		* )                    ## unknow option
			printf '%b\n' "${RED}Invalid option: ${1}${RESET}"
			printf '%b\n' "---"
			usage
			exit 1
			;;
	esac

	debug_message "Arguments management − \
${RED}${1}${COLOR_DEBUG} option managed."

	## Move to the next argument
	shift
	manage_arg=$((manage_arg+1))

	done

	debug_message "Arguments management − \
${RED}${manage_arg}${COLOR_DEBUG} argument(s) successfully managed."
else
	debug_message "Arguments management − \
No argument to manage."
fi

# }}}

main

exit 0
