#!/bin/bash

. ${TOOLKIT}-functions.sh

appname="nextcloud"
appnick="NextCloud"
module="srv-$appname"

version=$(jtconf $module.version)
zipfile=$(jtconf $module.zipfile)
repourl=$(jtconf $module.repourl)
instdir=$(jtconf $module.instdir)

user=$(jtconf apache.user)
group=$(jtconf apache.group)
owner="$user:$group"

tardir="$appname"


#config_dir=$(jtconf $module.config_dir)
#var_dir=$(jtconf $module.var_dir)
#log_dir=$(jtconf $module.log_dir)

db_host=$(jtconf $module.db_host)
db_port=$(jtconf $module.db_port)
db_name=$(jtconf $module.db_name)
db_user=$(jtconf $module.db_user)
db_pass=$(jtconf $module.db_pass)


here=$(pwd)

php_get_define()
{
	# grep can be tricky, since quotes can be ' or " and shell
	# doesn't escape well on quotes, so we preprocess input file
	# replacing all " with ', and only after we use grep
	#
	# more, you can have extra spaces in various places (php syntax, yeeee!!)
	#
	local match=$1
	local file=$2
	local out=

	out=$(tr '"' "'" <$file | grep "define\s*(\s*'$match'")
	echo "$out" | sed -e "s/.*,\s*'//" -e "s/'.*//"
}


# check the installed version
#
file="$instdir/inc/define.php"
cur_version=
need_install=false

[ -f $file ] && {
	# define('GLPI_VERSION', '10.0.10');
	cur_version=$(php_get_define "GLPI_VERSION" $file)
}

case $cur_version in
  $version)	echo "  $appnick: up-to-date (version=$cur_version)" ;;
  "")		need_install=true; echo "  $appnick: need to be installed" ;;
  *)		need_install=true; echo "  $appnick: must be upgraded (cur=$cur_version, new=$version)" ;;
esac

###cd $MODRUNDIR
[ -d /tmp/nextcloud ] || mkdir /tmp/nextcloud ###
cd /tmp/nextcloud ###

$need_install && {
	rm -f $zipfile
	wgetfile $repourl/$zipfile

	echo -e "  $appnick: extracting files ..."
	tar xfpz $zipfile

	[ -d $tardir ] || {
		echo "  ERROR: can't find '$tardir' dir in $zipfile"
		exit 1
	}
	[ -f $tardir/index.php ] || {
		echo "  ERROR: can't find '$tardir/index.php' file in $zipfile (wrong zipfile?)"
		exit 1
	}

	echo -n "  $appnick: installing $appname $version -> $instdir ... "
	(cd $tardir; find . | cpio -pdum $instdir/)

	###$var_dir/fix_perms
}

#### copy datadir structure
####
###echo -n "  updating datadir structure in '$var_dir' ... "
###cd $instdir/files
###find * -type d | cpio -pdum "$var_dir/"


###cd $instdir
###[ -d install ] && {

	#### setup db (must be created before)
	####
	###echo -e "\n  fresh install, create default database, please wait ... \n"

	###php bin/console db:install \
		###-H $db_host \
		###-P $db_port \
		###-d $db_name \
		###-u $db_user \
		###-p $db_pass \
		###-v || {
		###echo -e "\n   WARNING: db:install returned status=$?\n"
	###}

	#### rename install directory (for security reasons, too)
	###now=$(date '+%Y-%m-%d')
	###mv install install_$now
	###echo "   'install' directory rename to 'install_$now'"
###}

###$var_dir/fix_perms

$SOMETHING_CHANGED && {
	restart_service apache2 apache2
}

exit 0
