#!/bin/bash

. ${TOOLKIT}-functions.sh

appname="typemill"
appnick="TYPEMILL"
module="srv-$appname"
tmplog="/tmp/kusa-install-$module.log"

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

prjdir=$(jtconf $module.prjdir)		# main typemill project dir
instdir=$(jtconf $module.instdir)	# real typemill software installation dir

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

echo "
  TYPEMILL:
    prjdir	$prjdir
    instdir	$instdir
    user	$user
    group	$group
"


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


cur_version=$("$prjdir/bin/get_typemill_version")
need_install=false

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


$need_install && {
	tmpcontent="/tmp/kusa-tmpcontent"
	echo -e "  $appnick: extracting files to '$tmpcontent' ..."

	rm -rf $tmpcontent
	mkdir $tmpcontent
	cd $tmpcontent

	rm -f $srcfile
	wgetfile $repourl/$srcfile

	echo -e "  $appnick: extracting ..."
	unzip $srcfile >$tmplog 2>&1

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

	rm $srcfile $tmplog

	sysfiles="index.php  licence.md  plugins  system  themes"
	datafiles="cache  content  data  media  settings"

	# save previous installation?
	#
	[ "X$cur_version" != "X" ] && {
		echo -e "  $appnick: saving current installation files in $instdir.$cur_version"
		mkdir "$instdir.$cur_version"
		for file in $sysfiles
		do
			mv "$instdir/$file" "$instdir.$cur_version/"
		done
	}

	echo -en "  $appnick: installing "
	for file in $sysfiles
	do
		echo -n "$file "
		mv $file "$instdir/"
	done
	echo

	for file in $datafiles
	do
		[ -e "$instdir/$file" ] || {
			echo "  $appnick: install default data/dir '$file'"
			mv $file "$instdir/"
		}
	done
}

# records project settings
#
echo "$instdir" >"$prjdir/etc/instdir"

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

##$SOMETHING_CHANGED && {
	##restart_service apache2 apache2
##}

exit 0
