#!/bin/bash

PKG_NAME="vtigerCRM"
PKG_DIR="vtigercrm"
WEBSITE_ROOT="/var/services/web/$PKG_DIR"
CONF_FILE="config.inc.php"
DB_SETTING="modules/Install/models/Utils.php"
MIGRATE_DB_VERSION="0116"
INIT_DB_NAME="vtigercrm"
INIT_DB_USER="vtigercrm_user"
INFO_FILE="/usr/syno/etc/packages/$PKG_NAME/$PKG_DIR.conf"
MANUAL_DOWNLOAD_URL="https://sy.to/ablgm"

GetCurrentVersion()
{
	local ver_path="$WEBSITE_ROOT/vtigerversion.php"
	local cur_version=""
	if [ -s "$ver_path" ]; then
		cur_version=$(php -r "include('$ver_path'); echo \$vtiger_current_version;")
		echo "${cur_version}"
	fi
}

IsUpgradable()
{
	local current_version=$(GetCurrentVersion)
	local allow_versions="7.3 7.3.0 7.4.0"
	for allow_version in $allow_versions; do
		if [ "$current_version" == "$allow_version" ]; then
			true
			return
		fi
	done
	false
}

IsIncConfigEmpty()
{
	local prev_pkg_path="$1"
	local website_inc_config="${prev_pkg_path}/config.inc.php"
	[ ! -s "$website_inc_config" ];
}

CustomHasRunWebsiteSetup()
{
	local prev_pkg_path="$1"
	# this behavior refers to isInstalled() in vtigercrm/includes/main/WebUI.php
	if IsIncConfigEmpty $prev_pkg_path ; then
		false
		return
	fi
	true
}

CustomGetBackupPkgPath()
{
	local backup_prefix_path=$(CustomGetBackupPrefix)
	local backup_pkg_path=""
	local pkg_dir_540="vtigercrm-5.4.0"

	backup_pkg_path="$backup_prefix_path/$PKG_DIR"
	if [ ! -d "$backup_pkg_path" ]; then
		backup_pkg_path="$backup_prefix_path/$pkg_dir_540"
	fi
	echo "$backup_pkg_path"
}

CustomParseDBConf()
{
	local path="$1"
	local db_info="$2"
	local grep_info="$3"
	local info_output=$(CustomGetValueFromMetaFile "$db_info")

	if [ -z "$info_output" ]; then
		if [ -s "$path/$CONF_FILE" ]; then
			info_output=$(grep "dbconfig\['$grep_info'\]" "$path/$CONF_FILE" | cut -d"'" -f4)
		elif [ -s "$path/$DB_SETTING" ]; then
			info_output=$(grep "$grep_info' =>" "$path/$DB_SETTING" | cut -d"'" -f4)
		fi
	fi
	echo "$info_output"

}

CustomGetDBName()
{
	CustomParseDBConf "$1" "db_name" "db_name"
}

CustomGetDBUser()
{
	CustomParseDBConf "$1" "db_user" "db_username"
}

CustomGetDBPass()
{
	CustomParseDBConf "$1" "db_pass" "db_password"
}
