#!/bin/bash
set -e
# set -x
afpd_pid=`pidof /usr/sbin/afpd || :`
if ! test -z "$afpd_pid"
then
	echo "afpd with pid $afpd_pid is still running, stop it before upgrading the databases"
	echo "try 'rcatalk stop', which disconnects all netatalk clients without warning!"
	exit 1
fi
wdir=
oldcwd=`pwd`
for export_dir in "$@"
do
	export_dir="${export_dir%/}"
	export_dir="${export_dir%.AppleDB}"
	if test -d "${export_dir}/.AppleDB"
	then
		cd "${export_dir}/.AppleDB"
		if test -f cnid2.db
		then
			echo " - `pwd` has already a cnid2.db, skipping"
			continue
		fi
		wdir=`pwd`
		# db_update doesnt like it when the dbfiles are in $PWD
		cd /
		echo " - upgrading ${wdir}"
		cnid_access=`stat -c '%U:%G %a' "${wdir}/cnid.db"`
		for i in cnid didname mangle devino
		do
			echo -n "${i} "
			cp -Laf --remove-destination "${wdir}/${i}.db" "${wdir}/${i}.db.$$.backup"
			db_upgrade "${wdir}/${i}.db"
			db_dump -f "${wdir}/${i}.dump" "${wdir}/${i}.db"
			rm -f "${wdir}/${i}.db"
		done
		echo "... dump done"
		echo " - running cnid2_create"
		cd "${wdir}"
		cnid2_create
		rm -fv __db.* log.* *.db
		echo " - creating cnid2.db"
		db_load -f cnid2.dump cnid2.db
		chown -v "${cnid_access%% *}" cnid2.db
		chmod -v "${cnid_access##* }" cnid2.db
		ls -Alt
		echo " - done with ${wdir}"
	else
		echo " * skipping $export_dir"
	fi
done
