#!/bin/bash
set -e

#
# #############################################################################
# ## Alladdin, the all-add-in web server                                     ##
# #############################################################################
#
# @author Laurent GAERTNER <garthh@bagsbug.net>
# @version $Revision$
# @modifiedby $Author$
# @lastmodified $Date$
#
# #############################################################################
# ## Post installation script                                                ##
# #############################################################################
#
# LICENSE:
# Alladdin is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Alladdin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

. /etc/alladdin/alladdin.conf

## Création du répertoire /blog

if [ ! -d $wwwDir/blog ]
then
    mkdir $wwwDir/blog
    chown www-data:www-data $wwwDir/blog
fi

## Mise à jour si nécessaire

if [ -d /tmp/old-blog-to-update ] ; then
actuaDir=$PWD

	## Liste des comptes disposant d'un blog créé
	for blogAccount in $(ls $wwwDir/blog) ; do	

		## Suppression des anciens fichiers
		echo ""
		echo "Removing old blog files for ''$blogAccount''"
		thisDir=$(cat /dev/null)
		counter=0
		cd /tmp/old-blog-to-update
		for entry in $(ls -RBl | grep "^[^d|^total]" | awk '{print $NF}' | sed "s/://" | sed "s/.\//<:DIR:>/" | tail -n+2)
		do
			entryDir=$(echo $entry|grep "<:DIR:>"|sed "s/<:DIR:>//")
			if [ ! -z $entryDir ] ; then
				thisDir=$entryDir"/"
			else
				counter=$(($counter+1))
				if [ -f $wwwDir/blog/$blogAccount/$thisDir$entry ] ; then
					rm $wwwDir/blog/$blogAccount/$thisDir$entry
				fi
			fi
				echo -n -e "\r$counter files in progress\r"
		done
		echo "Task done, $counter files removed"

		## Copie des nouveaux fichiers
		echo "Installing new blog files"
		/usr/bin/cp-app blog $blogAccount
		/usr/bin/cp-ext blog $blogAccount
		
	done
cd $actuDir

rm -rf /tmp/old-blog-to-update
rm -rf /tmp/blog.conf

fi

exit 0
