#!/bin/bash

. ${TOOLKIT}-functions.sh

module="linfo"

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

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

tardir="$module-$version"


here=$(pwd)


# check the installed version
#
file="/etc/apache2/conf.d/ku-linfo.conf"
cur_version=
need_install=false

[ -f $instdir/index.php ] && {
	[ -f $file ] && {
		cur_version=$(grep 'Alias /linfo' $file | sed -e 's#.*/linfo-##')
	}
}

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

cd $RUNDIR

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

	echo -e "  extracting files ..."
	tar xfpz $tarfile

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

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

# manually install apache2 conf file (after package installation)
#
installfile "ku-linfo.conf" /etc/apache2/conf.d/ root:root 440


# cleanup and fix install dir perms (always)
#
chown -R $owner $instdir
find $instdir -type f -exec chmod 440 {} \;
find $instdir -type d -exec chmod 2770 {} \;

# config directories/files are moved to /etc and symlinked here
#
updatelink /etc/$module/config.inc.php $instdir/config.inc.php

# cleanup of old manual install
#
docdir=$(jtconf www.docs)
ls -d $docdir/linfo* /usr/share/linfo* 2>/dev/null | while :
do
	read path || break
	case $path in
	  *-$version)	continue ;; # skip
	esac
	echo "  cleanup old stuff: $path"
	rm -rf "$path"
done



$SOMETHING_CHANGED && {
	restart_service apache2 apache2
}

exit 0
