#!/bin/bash

. ${TOOLKIT}-functions.sh

appname="typemill"
appnick="TYPEMILL"
module="srv-$appname"

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

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

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


# check the installed version
#
file="$instdir/system/typemill/settings/defaults.yaml"
cur_version=
need_install=false

[ -f $file ] && {
	# version: '2.22.0'
	cur_version=$(grep "^version:" "$file" | sed -e 's/.* //' -e "s/'//g")
}

tmpinstdir=$instdir

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)"
  		tmpinstdir="tmp"
		mkdir "$tmpinstdir"
		;;
esac

cd "$tmpinstdir"

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

	echo -e "  $appnick: extracting files to '$instdir' ..."

	unzip $srcfile

	[ -d "system" ] || {
		echo "  ERROR: bad unzip (can't find 'system' dir in $srcfile)"
		exit 1
	}

	rm $srcfile
}

# updated?
#
[ "$tmpinstdir" != "$instdir" ] && {
	mv "$instdir" "$instdir.$cur_version"
	echo " $appnic: current install saved to $instdir.$cur_version"
	mv "$tmpinsdir" "$instdir"
}

# records project settings
#
prjdir=$(dirname "$instdir")

echo "$instdir" >"$prjdir/etc/instdir"

# fix permissions
#
"$prjdir/bin/fix_perms"

$SOMETHING_CHANGED && {
	restart_service apache2 apache2
}

exit 0
