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

usage() {                                                       # {{{

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

EXAMPLE :
    - Compare the current version installed on http://jellyfin.domain.tld:port
        check.jellyfin.update --url http://jellyfin.domain.tld:port/System/Info/Public

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

    -u,--url
        Specify the URL of the Jellyfin 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 jellyfin_url wasn't defined (argument,...) {{{
	if [ -z "${jellyfin_url}" ]; then
		### Display help message and exit
		usage
		error_message "Please set the Jellyfin's URL with -u|--url option." 3
	fi
	## }}}

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

	## TODO: Use --no-progress-meter instead of --silent
	##       when curl 7.74.x will be available on Debian Stable
	jellyfin_current_version=$(curl --silent "${jellyfin_url:=/dev/null}" | \grep -oP '(?<=Version":")[[:alnum:].]*')

	jellyfin_new_version=$("${script_wd}"/releasetags "${jellyfin_repo_url}" | grep -vE -- '(dev|rc|alpha|beta)' | head -n1 | sed 's/v//')

}
# }}}

main() {                                                        # {{{

	## Define all vars according the selected options
	define_vars

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

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

	else
		debug_message "Test Jellyfin version − \
The current version (${jellyfin_current_version}) is up-to-date."
		rm -f -- "${jellyfin_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 -q -E -- "^-+";
	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 -q -E -- "^-+"; do

	case "${1}" in
		-u|--url )             ## Set URL
			## Move to the next argument
			shift
			## Define jellyfin_url
			jellyfin_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 jellyfin_new_version_file
			jellyfin_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