#!/bin/sh
# Copyright (c) 2000-2021 Synology Inc. All rights reserved.

# Do NOT include SURVEILLANCE_INC_SCRP. While package center run preupgrade, SURVEILLANCE_INC_SCRP still old version
#SURVEILLANCE_INC_SCRP=/var/packages/SurveillanceStation/scripts/SurveillanceStationCommon
#. ${SURVEILLANCE_INC_SCRP}
CURR_SCRIPT_NAME="$(basename $0)"
SS_LOG_DIR="/var/log/surveillance"
SS_LOG_FILE="${SS_LOG_DIR}/surveillance.log"

SSDebugLog()
{
	local CurrDate="$(date +'%b %e %H:%M:%S')"
	local LogMsg="$1"
	local MaskVal="`umask`"

	#For creating log file with mode 666
	umask 0000
	echo "${LogMsg}"
	echo "${CurrDate} ${CURR_SCRIPT_NAME}: ${LogMsg}" >> "${SS_LOG_FILE}"
	umask "${MaskVal}"
}

SS_PKG_TMP_BASE_PATH="$SYNOPKG_PKGDEST_VOL/@sspkgprev"
SS_PRE_VERSION_PATH="/tmp/SurveillanceStation.upgrade"

SurveilInfoPath="/var/packages/SurveillanceStation/INFO"
SurveilDPPath="/var/packages/SurveillanceStation/target/device_pack"
SurveilDPPreUpgrade="${SurveilDPPath}/script/preupgrade"
SurveilLDPath="/var/packages/SurveillanceStation/target/local_display"
SurveilPath="/var/packages/SurveillanceStation/"
SSConf="${SurveilPath}target/etc/ss.conf"
SSSettingsConf="${SurveilPath}etc/settings.conf"

SZK_CMS_MODE="ss_cms_mode"
SZV_CMS_HOST="host"
CMS_DISABLED_FILE="/var/packages/SurveillanceStation/target/@SSData/AddOns/CMS/disabled"
SS_MIN_DVA_SUPPORT_CMS_VERSION="8.2.9-6391"
SS_SQLITE3="/var/packages/SurveillanceStation/target/bin/sqlite3"
SS_SYSTEM_DB="/var/packages/SurveillanceStation/target/system.db"
DEF_SYNOINFO_CONF="/etc.defaults/synoinfo.conf"

${SS_SQLITE3} --version
if [ $? == 0 ]; then
	SQLITE3_BIN=$SS_SQLITE3
else
	SQLITE3_BIN="sqlite3"
fi

SqliteSelectCount()
{
	${SQLITE3_BIN} -cmd ".timeout 200000" "$@" || echo 0
}

IsCmsHostHasEds14Slave()
{
	local CmsHost=$(get_key_value "${SSSettingsConf}" "${SZK_CMS_MODE}")
	local Eds14RecCnt=$(SqliteSelectCount ${SS_SYSTEM_DB} "SELECT count(id) FROM slaveds WHERE ds_model = 'EDS14'")

	if [ ! -f ${CMS_DISABLED_FILE} ] && [ ${SZV_CMS_HOST} == ${CmsHost} ] && [ ${Eds14RecCnt} -gt 0 ]; then
		echo true
	else
		echo false
	fi
}

IsCmsHostHasDvaSlave()
{
	local CmsHost=$(get_key_value "${SSSettingsConf}" "${SZK_CMS_MODE}")
	local DvaRecCnt=$(SqliteSelectCount "${SS_SYSTEM_DB}" "SELECT count(id) FROM slaveds WHERE ds_model like '%DVA%'")

	if [ ! -f ${CMS_DISABLED_FILE} ] && [ ${SZV_CMS_HOST} == ${CmsHost} ] && [ ${DvaRecCnt} -gt 0 ]; then
		echo true
	else
		echo false
	fi
}

IsX64Arch()
{
	local Arch=$(/bin/get_key_value "${SurveilInfoPath}" "arch")

	if [ "${Arch}" == "x86_64" ]; then
		echo true
	else
		echo false
	fi
}

IsSupportSynoface()
{
	local ModelName=$(/bin/get_key_value "${DEF_SYNOINFO_CONF}" "upnpmodelname")

	case "${ModelName}" in
		"DVA3219"|"DVA3221"|"DVA1622")
			echo true
			;;
		*)
			echo false
			;;
	esac
}

IsMergeFaceDatabase()
{
	if [ -f ${CMS_DISABLED_FILE} ]; then
		echo false
		return 0
	fi

	local CmsMode=$(/bin/get_key_value "${SSSettingsConf}" "${SZK_CMS_MODE}")
	local DvaRecCnt=$(SqliteSelectCount "${SS_SYSTEM_DB}" "SELECT count(id) FROM slaveds WHERE ds_model like '%DVA%'")

	if [ "false" == $(IsSupportSynoface) ]; then
		if [ ${SZV_CMS_HOST} != ${CmsMode} ] || [ ${DvaRecCnt} -le 0 ]; then
			echo false
			return 0
		fi
	else
		if [ ${SZV_CMS_HOST} == ${CmsMode} ] && [ ${DvaRecCnt} -le 0 ]; then
			echo false
			return 0
		fi
	fi

	echo true
}

IsHasDeepMD()
{
	local DeepMDCnt=$(SqliteSelectCount "${SS_SYSTEM_DB}" "SELECT count(id) FROM iva_setting WHERE analyze_type = 1")

	if [ false == $(IsSupportSynoface) ] || [ ${DeepMDCnt} -le 0 ]; then
		echo false
	else
		echo true
	fi
}

IsHasAllObjIntrusion()
{
	local AllObjIntrusionCnt=$(SqliteSelectCount "${SS_SYSTEM_DB}" "SELECT count(id) FROM iva_setting WHERE analyze_type = 8 and det_fg_obj = 0")

	if [ ${AllObjIntrusionCnt} -le 0 ]; then
		echo false
	else
		echo true
	fi
}

IsBeforeMinDvaSupportCmsVersion()
{
	local TargetSSVer=$(echo ${SS_MIN_DVA_SUPPORT_CMS_VERSION} | sed 's/\.//g' | sed 's/-//g')
	local CurrentSSVer=$(/bin/get_key_value "${SurveilInfoPath}" version)

	CurrentSSVer=$(echo ${CurrentSSVer} | sed 's/\.//g' | sed 's/-//g')

	if [ "${TargetSSVer}" -ge "${CurrentSSVer}" ]; then
		echo true
	else
		echo false
	fi
}

GetPreUpgradeVersion()
{
	local version=""
	local buildnumber=""

	# load buildnumber from dsm7_ss_buildnumber in settings.conf or ss.conf
	if [ "$(/bin/get_key_value "/etc.defaults/VERSION" "majorversion")" -ge "7" ]; then
		buildnumber="$(/bin/get_key_value "${SSSettingsConf}" "dsm7_ss_buildnumber")"

		if [ -z "$buildnumber" ]; then
			buildnumber="$(/bin/get_key_value "${SSConf}" "dsm7_ss_buildnumber")"
		fi
	fi

	version="$(/bin/get_key_value "${SurveilInfoPath}" "version")"
	if [ -n "$buildnumber" ]; then
		version="$(echo "${version}" | cut -d'-' -f1)-${buildnumber}"
	fi

	echo "$version"
}

main()
{
	local BlockUpgrade=false
	local PreVer="$(GetPreUpgradeVersion)"

	if [ -z ${ui_confirmed_eds14_eol} ] || [ true != ${ui_confirmed_eds14_eol} ]; then
		if [ true == $(IsCmsHostHasEds14Slave) ]; then
			SSDebugLog "Set BlockUpgrade: Cms host has eds14 slave and not ui upgrade"
			BlockUpgrade=true
		fi
	fi

	if [ -z ${ui_confirmed_suggest_x64_host} ] || [ true != ${ui_confirmed_suggest_x64_host} ]; then
		if [ true == $(IsCmsHostHasDvaSlave) ] && [ false == $(IsX64Arch) ] && [ true == $(IsBeforeMinDvaSupportCmsVersion) ]; then
			SSDebugLog "Set BlockUpgrade: Cms host is not x64 and have dva slaves."
			BlockUpgrade=true
		fi
	fi

	if [ -z ${ui_confirmed_face_database_merge} ] || [ true != ${ui_confirmed_face_database_merge} ]; then
		if [ true == $(IsMergeFaceDatabase) ] && [ true == $(IsBeforeMinDvaSupportCmsVersion) ]; then
			SSDebugLog "Set BlockUpgrade: not merge face database"
			BlockUpgrade=true
		fi
	fi

	if [ -z ${ui_confirmed_remove_deep_md} ] || [ true != ${ui_confirmed_remove_deep_md} ]; then
		if [ true == $(IsHasDeepMD) ] && [ true == $(IsBeforeMinDvaSupportCmsVersion) ]; then
			SSDebugLog "Set BlockUpgrade: not remove deep md"
			BlockUpgrade=true
		fi
	fi

	if [ -z "${ui_ss90_patch_note}" ] || [ true != "${ui_ss90_patch_note}" ]; then
		if [ -z "$PreVer" ]; then
			SSDebugLog "Skip check Surveillance Station 9.0 patch note due to fetch PreVer failed"
		elif [ "$(echo "$PreVer" | cut -d '.' -f 1)" -lt 9 ]; then
			SSDebugLog "Set BlockUpgrade: Surveillance Station 9.0 patch note"
			BlockUpgrade=true
		fi
	fi

	if [ -z ${ui_confirmed_remove_all_obj_intrusion} ] || [ true != ${ui_confirmed_remove_all_obj_intrusion} ]; then
		if [ true == $(IsHasAllObjIntrusion) ]; then
			SSDebugLog "Set BlockUpgrade: not remove all object intrusion"
			BlockUpgrade=true
		fi
	fi

	if [ true == "${cms_upgrade_skip_note}" ]; then
		SSDebugLog "Force upgrade by cms."
		BlockUpgrade=false
	fi

	if [ true == ${BlockUpgrade} ]; then
		SSDebugLog "Block upgrade."
		echo -n "backup:app_err_upgrade" > $SYNOPKG_TEMP_LOGFILE
		return -1
	fi

	# Remove old pkg backup
	if [ -d "$SS_PKG_TMP_BASE_PATH" ]; then
		rm -rf "$SS_PKG_TMP_BASE_PATH"
	fi
	mkdir "$SS_PKG_TMP_BASE_PATH"

	if [ -n "$PreVer" ]; then
		echo "PreVer=${PreVer}" > "$SS_PRE_VERSION_PATH"
	fi

	# Backup Device Pack
	if [ -d $SurveilDPPath ]; then
		cp -aR $SurveilDPPath "$SS_PKG_TMP_BASE_PATH"
		$SurveilDPPreUpgrade
	fi

	# Backup Local Display on NVR platform
	if [ -d $SurveilLDPath ]; then
		cp -aR $SurveilLDPath "$SS_PKG_TMP_BASE_PATH"
	fi

	# Backup last synoface DB version
	if [ -f "${SurveilPath}/target/synodva/etc/db_version" ]; then
		cp -a ${SurveilPath}/target/synodva/etc/db_version ${SurveilPath}/etc/db_version.last
	fi
}

main "$@"
