#!/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"

# Default values for some vars
readonly ADGUARD_BIN_DEFAULT="/opt/adguard/AdGuardHome/AdGuardHome"
readonly ADGUARD_NEW_VERSION_FILE_DEFAULT="/tmp/.adguard.upgrade"
# }}}

usage() {                                                       # {{{

	cat <<- EOF
usage: $PROGNAME [-b|-d|-f|-h|-u]
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

    - Download ARMv7 version if it's a newer version
        check.adguard.update --url "https://static.adguard.com/adguardhome/release/AdGuardHome_linux_armv7.tar.gz"

OPTIONS :
    -b,--bin
        Specify the path of AdGuard Home's binary
        (default: ${ADGUARD_BIN_DEFAULT}).

    -f,--file
        Set the path to the temp file that will be create and
        that should be monitored (default: ${ADGUARD_NEW_VERSION_FILE_DEFAULT}).

    -u,--url
        Set the URL to use to download the last version of AdGuard Home (default: empty).
        See the list of possible URLs on :
        https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started

    -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}"

}
# }}}
is_var_nonempty() {                                             # {{{

	local_var_nonempty="${1}"

	## Return False by default
	return_var_nonempty="1"

	debug_message "is_var_nonempty − \
Test var: ${1}."
	### Test if var lenght is nonzero and set return value to True
	[ -n "${local_var_nonempty}" ] && return_var_nonempty="0"

	unset local_var_nonempty

	return "${return_var_nonempty}"
}
# }}}
define_vars() {                                                 # {{{

	## If adguard_bin wasn't defined (argument,...) {{{
	if [ -z "${adguard_bin}" ]; then
		### Use default value
		adguard_bin="${ADGUARD_BIN_DEFAULT}"
	fi
	## }}}
	## If adguard_new_version_file wasn't defined (argument,...) {{{
	if [ -z "${adguard_new_version_file}" ]; then
		### Use default value
		adguard_new_version_file="${ADGUARD_NEW_VERSION_FILE_DEFAULT}"
	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 with error 3
	is_var_empty "${adguard_new_version}" \
		&& error_message "adguard_new_version seems empty (${adguard_new_version}), exit without error." 3
	## }}}

	## 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}"
		## }}}

		## If an URL was set {{{
		if is_var_nonempty "${adguard_new_version_url}"; then
			debug_message "Download AdGuard Home new version − \
Download new archive from ${adguard_new_version_url} and extract to /tmp/ ."
			wget --quiet "${adguard_new_version_url}" -O - | tar --extract --gzip --directory=/tmp --strip-components 2 ./AdGuardHome
			mv --force /tmp/AdGuardHome "${adguard_bin}.to.upgrade.${adguard_new_version}" \
				|| error_message "Can't move /tmp/AdGuardHome to ${adguard_bin}.to.upgrade.${adguard_new_version} ."  4
		fi
		## }}}

	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}"
			;;
		-u|--url )             ## Set new version URL
			## Move to the next argument
			shift
			## Define adguard_new_version_url
			adguard_new_version_url="${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