#!/bin/sh -e

. /usr/share/debconf/confmodule

db_version 2.0

if [ "$1" = "reconfigure" ] ; then
	# Rotate old configuration
	config="/etc/dolibarr/apache.conf"
	for i in $(seq 8 -1 0) ; do
		if [ -f ${config}.$i ]
			then mv ${config}.$i ${config}.$(($i +1))
		fi
	done
	mv ${config} ${config}.0
fi
step=0
finished="false"

db_capb backup
while ! $finished ; do
	skip="false"
	forward=1
	backward=1
	password=""
	confirm=""
	case $step in
		0)	# Prompt user for notes.
			db_beginblock
				db_input low "dolibarr/configuration/note" || true
			db_endblock
			backward=0
		;;
		1)	# Ask for web server type.
			db_input medium "dolibarr/webserver" || true
		;;
		2)	# Ask on wich host the DBMS is installed.
			db_input critical "dolibarr/db/host" || true
			# Skip previous step.
			backward=1
		;;
		3)	# Get the database administrator name and password.
			db_beginblock
				db_input critical "dolibarr/db/admin/name" || true
				db_input critical "dolibarr/db/admin/password" || true
			db_endblock
			# Skip previous step.
			backward=1
		;;
		4)	# Ask for DB name.
			db_input critical "dolibarr/db/name" || true
		;;
		5)	# Get the DBMS account username
			db_input critical "dolibarr/db/user/name" || true
		;;
		6) # Get the DBMS account password
			db_fset "dolibarr/db/user/password/mismatch" "seen" "false" || true
			db_beginblock
				db_input critical "dolibarr/db/user/password" || true
				db_input critical "dolibarr/db/user/password/confirm" || true
			db_endblock
		;;
		7)	# Check if passwords match.
			db_get "dolibarr/db/user/password"
			password="$RET"
			db_get "dolibarr/db/user/password/confirm"
			confirm="$RET"
			if [ "$password" != "$confirm" ] ; then
				# Reset the template used
				db_reset "dolibarr/db/user/password" || true
				db_fset  "dolibarr/db/user/password" "seen" "false" || true
				db_reset "dolibarr/db/user/password/confirm" || true
				db_fset  "dolibarr/db/user/password/confirm" "seen" "false" || true
				# Promt the user
				db_input critical "dolibarr/header/password/mismatch" || true
				# Do one step back anyway.
				forward=-1
			else
				# Do not prompt, go to the next step.
				skip="true"
			fi
		;;
		8)	# Ask for deleting all the database on package purge.
			db_input medium "dolibarr/postrm" || true
			onsuccess='finished="true"'
			# Skip previous step
			backward=2
		;;
		*)
			skip="true"
			message="Unknown step #$tep."
			if [ $step -lt 0 ] ; then
				step=-1
			elif [ $step -gt 11 ] ; then
				finished="true"
			fi
		;;
	esac
	
	if $skip ; then
		next=$(($step + 1))
		eval $onsuccess
		onsuccess=''
	else
		db_title "dolibarr" || true
		if db_go ; then
			next=$(($step + $forward))
			eval $onsuccess
			onsuccess=''
		else
			next=$(($step - $backward))
			onsuccess=''
		fi
	fi
	step=$next
done

db_stop
exit 0
