#!/bin/bash
#
CMD=$(basename $0)

set -e
set -u

usage()
{
	exit 1
}

cleanup()
{
	rm -f $tmpfile
}

need_update()
{
	revno="0"
	upd="0"

	[ -f $verfile ] && {
		revno=$(grep "^revno_$module=" $verfile | sed -e 's/.*=//' -e "s/'//g")
	}
	[ -f $updfile ] && {
		upd=$(grep "^revno_$module=" $updfile | sed -e 's/.*=//' -e "s/'//g")
	}
	echo -n "local=$revno update=$upd "
	[ "$revno" != "$upd" ] && {
		echo "update needed"
		return 0
	}
	echo "up to date"
	return 1
}


sanity_checks()
{
	local file="etc/openerp-server.conf"
	[ -f $file ] || {
		echo "file '$file' not exists, wrong directory?" >&2
		exit 1
	}
	[ -d old ] || {
		sudo jtmkpath -v old
	}
}


wgetfile()
{
	local file=$1
	local url=$2

	echo    " getting $url"
	echo -n "      -> $file ... "
	rm -f $file.tmp
	wget -O $file.tmp $url >$tmpfile 2>&1 || {
		echo "ERROR"
		cat $tmpfile
		rm -f $file.tmp
		return 1
	}
	echo "ok"
	rm -f $tmpfile
	rm -f $file
	mv $file.tmp $file
	return 0
}

# (MAIN)

verfile="version.txt"
updfile="updates.txt"
tmpfile=$(mktemp /tmp/$CMD-XXXXXX)
repos=$(kusa-conf service.repos)
changed=false

repourl="ftp://$repos/pub/openerp"

trap "echo '*INTR*'; cleanup; exit 255" 1 2 3
trap "cleanup" EXIT

sanity_checks

wgetfile $updfile $repourl/version.txt

modules=$(cat $updfile | sed -e 's/revno_//' -e 's/=.*//')

for module in $modules
do
	echo -en "\n CHECKING $module: "

	revno=0
	upd=0

	need_update $module || continue

	tarfile="openerp7-$module-$upd.tar.bz2"
	wgetfile $tarfile $repourl/$tarfile

	[ -d $module ] && {
		[ -d old/$module ] && {
			echo "ERROR, dir old/$module exists" >&2
			echo "  (left from a previous update? remove it before proceeding)" >&2
			exit 1
		}
		mv $module old/.
	}
	echo -n " extracting files ... "
	tar xfpj $tarfile
	echo "ok"
	rm -f $tarfile
	changed=true
done

echo -en "\n FIX PERMS ... "
chown -R openerp:openerp .
echo "ok"

echo -e "\n INSTALLING PATCHES"
cd patches
make
cd ..

mv $updfile $verfile
exit 0
