###
### some global variables etc
###
dbc_go(){
	local need_admin_pw

	. /usr/share/dbconfig-common/dpkg/common
	dbc_config $@

	need_admin_pw="yup"

	if [ "$dbc_command" = "upgrade" ]; then
		###
		### make a note that we're upgrading so that the soon-to-come
		### postinst call won't try and recreate users, etc
		###
		db_set $dbc_package/performing_upgrade true
	fi

	if [ "$dbc_command" = "remove" ]; then
		###
		### ask the admin if we should help with removal
		###
		
		if [ "$dbc_remove" ]; then 
			db_set $dbc_package/dbconfig-remove "$dbc_remove"
		fi
		db_fset $dbc_package/dbconfig-remove seen false
		db_input high $dbc_package/dbconfig-remove || true
		db_go || true
		db_get $dbc_package/dbconfig-remove
		dbc_remove="$RET"

		if [ "$dbc_remove" != "true" ]; then
			return 0;
		fi

		###
		### get all the debconf settings we need
		###

		# get the db server
		db_get $dbc_package/remote/host && dbc_dbserver="$RET"

		# get the name of the database created
		db_get $dbc_package/db/dbname && dbc_dbname="$RET"

		# get the admin user
		db_get $dbc_package/$dbc_dbtype/admin-user && dbc_dbadmin="$RET"

		# get the app user password
		db_get $dbc_package/$dbc_dbtype/app-pass && dbc_app_pass="$RET"

		###
		### perform a few sanity checks on the data
		###

		# if dbserver is unset, that means localhost.  
		if [ -z "$dbc_dbserver" ]; then 
			# if the server is local, only allow connections from localhost
			dbc_dballow="localhost"
		else
			# otherwise, only tell the remote database to allow from us
			dbc_dballow=`hostname`
		fi
		
		###
		### ask the admin if the database should be purged
		###
		db_input high $dbc_package/purge || true
		db_go || true
		db_get $dbc_package/purge
		dbc_purge="$RET"

		if [ "$dbc_dbtype" = "pgsql" ] && \
		   [ "$dbc_authmethod_admin" = "ident" ]; 
		then
			need_admin_pw=""
		fi

		if [ "$dbc_purge" = "true" ]; then
			# get the admin user password
			if [ "$need_admin_pw" ]; then
				dbc_get_admin_pass
			fi

			# dump the database into a temporary file
			_dbc_now=`date +%Y-%m-%d-%H.%M`
			_dbc_dbfile=`mktemp /var/tmp/$dbc_package.$dbc_dbname.$_dbc_now.$dbc_dbtype.XXXXXX`
			# XXX error checking here
			echo dbconfig-common: dumping $dbc_dbtype database $dbc_dbname to $_dbc_dbfile >&2
			$dbc_dump_cmd > $_dbc_dbfile
			echo dbconfig-common: dropping $dbc_dbtype database $dbc_dbname >&2
			$dbc_dropdb_cmd || dbc_remove_error "dropping database"
			[ "$dbc_tried_again" ] && return 0

			echo dbconfig-common: revoking privileges for user $dbc_dbuser on $dbc_dbname > /dev/stderr
			$dbc_dropuser_cmd
		fi
	fi
}
