#!/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"

zipdir="$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)

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

[ -f $file ] && {
	# $OC_VersionString = '32.0.3';
	cur_version=$(grep '^\$OC_VersionString' "$file" | sed -e 's/.*=\s*//' -e "s/['\";]//g");
}

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

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

	echo -e "\n  $appnick: extracting files ...\n"
	unzip $zipfile

	[ -d $zipdir ] || {
		echo "  ERROR: can't find '$zipdir' dir in $zipfile"
		exit 1
	}
	[ -f $zipdir/index.php ] || {
		echo "  ERROR: can't find '$zipdir/index.php' file in $zipfile (wrong zipfile?)"
		exit 1
	}
	echo -e "\n $appnick: extraction done\n"

	echo -n "  $appnick: installing $appname $version -> $instdir ... "
	(cd $zipdir; find . | cpio -pdum $instdir/)
	echo -e "\n $appnick: installation done\n"
}

$instdir/fix_perms

$SOMETHING_CHANGED && {
	restart_service apache2 apache2
}

exit 0
