#!/bin/sh

# Read configuration variable file if it is present
[ -r /etc/default/cyrus-imapd ] && . /etc/default/cyrus-imapd

if [ -n "$CONF" ]; then
       	[ -r "$CONF" ] || ( echo Could not read config file $CONF; exit 1)
else
       	CONF=/etc/imapd.conf
fi

check_hardwired_config() {
    grep -qE '^PACKAGE_VERSION[[:blank:]]+([0-9]+:|)3[.]0' \
	/usr/lib/cyrus/cyrus-hardwired-config.txt >/dev/null 2>&1
    return $?
}

verifydb() {
   while read -r DBKEY DBVALUE ; do
	match=`sort -u < $1 | gawk "/^${DBKEY}[[:blank:]]/ { print \\$2 }"`
	[ "x${match}" != "x${DBVALUE}" ] && return 0
   done
   return 1
}

createdir() {
# $1 = user
# $2 = group
# $3 = permissions (octal)
# $4 = path to directory
    [ "$VERBOSE" = "yes" ] && OPT="-c"
    [ -d "$4" ] || mkdir -p "$4"
    chown $OPT -h "$1:$2" "$4"
    chmod $OPT "$3" "$4"
}

missingstatoverride () {
    echo "$0: You are missing a dpkg-statoverride on $1.  Add it." >&2
    exit 1
}

fixdirs () {
	dir=$(dpkg-statoverride --list /var/run/cyrus) \
		|| missingstatoverride /var/run/cyrus
	[ -z "$dir" ] \
		|| createdir $dir
	dir=$(dpkg-statoverride --list /var/run/cyrus/socket) \
		|| missingstatoverride /var/run/cyrus/socket
	[ -z "$dir" ] \
		|| createdir $dir
}

#
# Function that checks consistency of used database backends
#
check_database_backends() {
    # Verify consistency of database backends
    [ -f /usr/lib/cyrus/cyrus-db-types.active ] && {
        # is it safe to start cyrmaster? compare "key value" pairs
        # from the (old) active database types file with the new one
	( sort -u /usr/lib/cyrus/cyrus-db-types.active \
	    | grep DBENGINE \
	    | verifydb /usr/lib/cyrus/cyrus-db-types.txt \
	    ) && {
	    return 1
	}
    }
    return 0
}

# Check for the sanity of the cyrus-imapd environment
if ! check_hardwired_config; then
    echo "$0: cyrus-hardwired-config.txt doesn't contain current version"
    echo "$0: of the package (2.2 or 2.4)"
    exit 1
fi

if ! check_database_backends; then
    /usr/lib/cyrus/bin/upgrade-db || {
	echo "$0: Database backends mismatch and automatic upgrade failes!" 1>&2
	echo "$0: You must manually verify and update the Cyrus databases" 1>&2
	echo "$0: to the new backends." 1>&2
	echo "$0: Please refer to /usr/share/doc/cyrus-common/README.Debian*" 1>&2
	echo "$0: for instructions." 1>&2
	echo
	echo "$0: Cyrmaster not started."
	exit 6
    }
fi

case "$1" in
    start)
	fixdirs;

        # Clean stale entries	
	CONFIGDIR="$(gawk '/^configdirectory:[[:blank:]]/ {print $2}' $CONF)"
	LOCK_DIR="$(gawk '/^mboxname_lockpath:[[:blank:]]/ {print $2}' $CONF)"
	PROC_DIR="$(gawk '/^proc_path:[[:blank:]]/ {print $2}' $CONF)"
	[ -z "$LOCK_DIR" ] && LOCK_DIR="$CONFIGDIR/lock"
	[ -z "$PROC_DIR" ] && PROC_DIR="$CONFIGDIR/proc"

	[ -d "$LOCK_DIR" ] && find "$LOCK_DIR" -mindepth 1 -depth -size 0 -delete
	[ -d "$PROC_DIR" ] && find "$PROC_DIR" -mindepth 1 -depth -name '[0-9]*' -delete
	;;
    *)
	;;
esac

exit 0
