#!/bin/sh
# Purpose {{{
## Create a temp file (to monitor) if an upgrade is available for Sickchill
## project on Github.
## It's based on the Sickchill URL site 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 Sickchill URL as first argument, eg.
#00 20 * * * root /opt/repos/ipr.scripts/github/check_sickchill_update http://sickchill.domain.tld:port/System/Info/Public
### 3. Monitor the temp file : /tmp/.github.sickchill.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}")
sickchill_repo_url="https://github.com/SickChill/SickChill"
# }}}

usage() {                                                       # {{{

	cat <<- EOF
usage: $PROGNAME [-d|-f|-h] --url http://sickchill.domain.tld:port/config
Compare current version of an installed Sickchill site and the last available.

EXAMPLE :
    - Compare the current version installed on http://sickchill.domain.tld:port
        check.sickchill.update --url http://sickchill.domain.tld:port/config

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

    -u,--url
        Specify the URL of the Sickchill instance to check.

    -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}"
}
# }}}
define_vars() {                                                 # {{{

	## If sickchill_url wasn't defined (argument,...) {{{
	if [ -z "${sickchill_url}" ]; then
		### Display help message and exit
		usage
		error_message "Please set the Sickchill's URL with -u|--url option." 3
	fi
	## }}}

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

	## TODO: Use --no-progress-meter instead of --silent
	##       when curl 7.74.x will be available on Debian Stable
	sickchill_current_version=$(curl --silent "${sickchill_url:=/dev/null}" | \grep --only-matching --perl-regexp '(?<=https://github.com/SickChill/SickChill/releases/tag/v)[[:alnum:].]*')

	sickchill_new_version=$("${script_wd}"/releasetags "${sickchill_repo_url}" | grep --invert-match --extended-regexp -- '(dev|rc|-)' | head --lines=1 | sed 's/v\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/')

}
# }}}

main() {                                                        # {{{

	## Define all vars according the selected options
	define_vars

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

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

	else
		debug_message "Test Sickchill version − \
The current version (${sickchill_current_version}) is up-to-date."
		rm --force -- "${sickchill_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
		-u|--url )             ## Set URL
			## Move to the next argument
			shift
			## Define sickchill_url
			sickchill_url="${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 sickchill_new_version_file
			sickchill_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
	error_message "Please at least give an URL with -u|--url option. See --help for more informations." 2
fi

# }}}

main

exit 0
