#!/bin/sh

# Copyright (c) 2016, Justin D Holcomb All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Check for chyves updated
__check_for_chyves_update() {
	if [ "$_CHECK_FOR_UPDATES" != "off" ]; then
		[ "$_CHECK_FOR_UPDATES" = "daily" ] && local _num_of_updays=1
		[ "$_CHECK_FOR_UPDATES" = "monthly" ] && local _num_of_updays=30
		[ "$_CHECK_FOR_UPDATES" = "always" ] && local _num_of_updays=0
		[ -z "$_num_of_updays" ] && local _num_of_updays=7
		local _check_again_date=`date -v -${_num_of_updays}d +"%Y%m%d"`

		if [ "$_CHECK_FOR_UPDATES_LAST_CHECK_STATUS" -eq 1 ]; then
			__log 1 "NEW VERSION of chyves available. Check $_PROJECT_URL_GIT/tree/$_VERSION_BRANCH or run 'chyves upgrade'."
		elif [ "$_check_again_date" -ge "$_CHECK_FOR_UPDATES_LAST_CHECK" ]; then
			__log 1 "Checking for newer version of chyves on the $_VERSION_BRANCH branch from $_CHECK_FOR_UPDATES_URL."
			local _fetched_version_library=$( fetch --timeout $_CHECK_FOR_UPDATES_TIMEOUT_SECONDS --quiet -o - --user-agent="chyves $_VERSION_LONG ( $_OS $_OS_VERSION_REL $_OS_VERSION_DATE $_OS_VERSION_REV $_OS_VERSION_FREENAS ; ${_CHECK_FOR_UPDATES_UNIQUE_ID}; )" $_CHECK_FOR_UPDATES_URL )
			local _grepped_version=$( echo "$_fetched_version_library" | grep -E '^_VERSION_INT=' | cut -d'"' -f2 )

			if [ -z "$( echo "$_grepped_version" | grep -E '^[0-9]{1,}$' )" ] || [ -z "$_grepped_version" ]; then
				__log 1 "Unable to obtain current available version information from $_CHECK_FOR_UPDATES_URL after $_CHECK_FOR_UPDATES_TIMEOUT_SECONDS seconds."
			elif [ "$_grepped_version" -gt "$_VERSION_INT" ]; then
				__write_property_value_to_config_file "global" "check_for_updates_last_check" "$_DATE_YMD"
				__log 1 "NEW VERSION ($_grepped_version) of chyves available. Check $_PROJECT_URL_GIT/tree/$_VERSION_BRANCH or run 'chyves upgrade'."
				_CHECK_FOR_UPDATES_LAST_CHECK_STATUS="1"    # This is for __install_from_github
				__write_property_value_to_config_file "global" "check_for_updates_last_check_status" "1"
			elif [ "$_grepped_version" -eq "$_VERSION_INT" ]; then
				local _next_check_date=`date -v +${_num_of_updays}d +"%Y%m%d"`
				__write_property_value_to_config_file "global" "check_for_updates_last_check" "$_DATE_YMD"
				__log 1 "On current version, will check again on: $_next_check_date"
				__write_property_value_to_config_file "global" "check_for_updates_last_check_status" "0"
			fi
		fi
	fi
}

# Install latest chyves version from GitHub using specific branch.
__install_from_github() {
	local _branch_override="$1"
	local _tmp_dir="/tmp/$_UUID_GUEST_USE"
	_CHECK_FOR_UPDATES=always                 # This forces a check now.
	_CHECK_FOR_UPDATES_LAST_CHECK_STATUS="0"  # This forces a check now.

	# Handling for branch to upgrade to. Or if this just a check.
	if [ -n "$_branch_override" ]; then
		if [ "$_branch_override" = "check" ]; then
			exit
		elif [ "$_branch_override" = "master" ] || [ "$_branch_override" = "dev" ]; then
			local _upgrade_branch="$_branch_override"
		else
			__fault_detected_exit "Unrecognized parameter '$1', valid branches are 'master' or 'dev'."
		fi
	else
		local _upgrade_branch="$_VERSION_BRANCH"
	fi

	# Needed for switching between branches.
	_CHECK_FOR_UPDATES_URL="$_PROJECT_URL_GIT/raw/${_upgrade_branch}/sbin/chyves"
	__check_for_chyves_update

	# This will be changed to "1" when an update is avaible.
	if [ "$_CHECK_FOR_UPDATES_LAST_CHECK_STATUS" = 0 ]; then
		__log 1 "On the latest version already."
		exit
	fi

	__log 1 "Installing latest version of chyves from GitHub, using branch: $_upgrade_branch"

	__log 2 "This install is currently running $_VERSION_BRANCH branch of chyves on version: $_VERSION_LONG"

	__log 2 "Checking network connectivity to github.com... " -n
	ping -o -q -c 2 github.com > /dev/null 2>&1
	if [ "$?" != 0 ]; then
		__log 1 "Unable to ping Github.com, exiting."
		exit
	else
		__log 2 "success."
	fi

	__log 2 "Creating directory: $_tmp_dir"
	mkdir $_tmp_dir > /dev/null 2>&1
	[ "$?" != 0 ] && __fault_detected_exit "Unable to create folder in temporary directory '$_tmp_dir'."

	# Remove temporary working directory.
	__install_from_github_micro_cleanup() {
		__log 2 "Removing temporary working folder... " -n
		cd ~
		rm -rf $_tmp_dir > /dev/null 2>&1
		if [ "$?" != 0 ]; then
			__log 2 "Unable to delete folder '$_tmp_dir', you will need to manually remove it."
		else
			__log 2 "done."
		fi
		exit
	}

	__log 2 "Changing to directory '$_tmp_dir'... " -n
	cd $_tmp_dir > /dev/null 2>&1
	if [ "$?" != 0 ]; then
		__log 1 "Unable to change to temporary directory '$_tmp_dir'. Cleaning up and exiting."
		__install_from_github_micro_cleanup
	else
		__log 2 "done."
	fi

	__log 2 "Fetching latest code from $_upgrade_branch branch... " -n
	fetch --quiet https://github.com/chyves/chyves/archive/$_upgrade_branch.zip -o $_tmp_dir/ > /dev/null 2>&1
	if [ "$?" != 0 ]; then
		__log 1 "Unable to retreive latest chyves code on branch $_upgrade_branch from Github.com"
		exit
	else
		if [ ! -f "$_tmp_dir/$_upgrade_branch.zip" ]; then
			__log 1 "Missing downloaded zip file from Github."
			__install_from_github_micro_cleanup
		else
			__log 2 "done."
		fi
	fi

	__log 2 "Extracting archive file '$_upgrade_branch.zip'... " -n
	unzip $_tmp_dir/$_upgrade_branch.zip > /dev/null 2>&1
	if [ "$?" != 0 ]; then
		__log 1 "Unable to retreive latest chyves code on $_upgrade_branch branch from Github.com"
		__install_from_github_micro_cleanup
	else
		__log 2 "done."
	fi

	__log 2 "Changing to directory '$_tmp_dir/chyves-$_upgrade_branch'... " -n
	cd $_tmp_dir/chyves-$_upgrade_branch > /dev/null 2>&1
	if [ "$?" != 0 ]; then
		__log 1 "Unable to change to temporary directory '$_tmp_dir/chyves-$_upgrade_branch'. Cleaning up and exiting."
		__install_from_github_micro_cleanup
	else
		__log 2 "done."
	fi

	__log 2 "Installing new version of chyves... " -n
	make install > /dev/null 2>&1
	if [ "$?" != 0 ]; then
		__log 1 "Failed to install chyves."
		__install_from_github_micro_cleanup
	else
		__log 2 "done."
		__write_property_value_to_config_file "global" "check_for_updates_last_check_status" "0"
	fi

	__log 1 "The following version of chyves is now installed:"
	chyves version
	__log 1 "You may need to update the datasets and/or guests."

	__install_from_github_micro_cleanup
}
