PKG=#DZ-PKG#
INSTANCE=#DZ-INSTANCE#
ZVER=#DZ-ZVER#

add_products()
{
    products="#DZ-PRODUCTS#"
    if [ -n "$products" ]; then
        dzhandle -z $ZVER add-product --lazy $INSTANCE $products
    fi
}

case "$1" in
  abort-deconfigure|abort-remove|abort-upgrade)
    ;;
  configure)
    if dzhandle -z $ZVER show-instance $INSTANCE >/dev/null 2>&1; then
        # instance already exists
        echo "Zope$ZVER instance '$INSTANCE' already exists".
        add_products
        if ! dzhandle -z $ZVER zopectl $INSTANCE start; then
            echo "Could not start zope instance $INSTANCE. Please check"
            echo "for errors running the instance by hand:"
            echo "  /var/lib/zope$ZVER/instance/$INSTANCE/runzope"
        fi
    else
        if [ -d /var/lib/zope$ZVER/instance/$INSTANCE ] && \
                [ ! -f /var/lib/zope$ZVER/instance/$INSTANCE/var/Data.fs ]; then
            db_get $PKG/remove-instance-without-data
            removal="$RET"
            if [ "$removal" = abort ]; then
                echo >&2 "don't touch /var/lib/zope$ZVER/instance/$INSTANCE"
                exit 1
            fi
        else
            clean_install=yes
        fi
        db_get $PKG/admin-user
        user="$RET"
        db_get $PKG/admin-password
        password="$RET"
        if echo "$user:$password" | grep -vq '^[a-zA-Z][a-zA-Z0-9]*:[^:][^:]*$'; then
            echo >&2 "found invalid user and/or password"
            exit 1
        fi
        db_get $PKG/instance-http-port
        port="$RET"
        
        # set the install policy to manual
        if dzhandle -z $ZVER make-instance -u "$user:$password" $INSTANCE \
            --addon-mode=#DZ-ADDON-MODE# --restart=#DZ-RESTARTPOLICY# -t #DZ-ADDON-TECHNIQUE# \
            --service-port "$port"
        then
            # overwrite password in debconf database
            db_set $PKG/admin-password ""
            db_set $PKG/admin-password-confirmation ""
            add_products
            if ! dzhandle -z $ZVER zopectl $INSTANCE start; then
                echo "Could not start zope instance $INSTANCE. Please check"
                echo "for errors running the instance by hand:"
                echo "  /var/lib/zope$ZVER/instance/$INSTANCE/runzope"
            fi
        else
            # remove, what we created
            if [ "$clean_install" = yes ] && [ "$removal" != abort ]; then
                rm -rf /var/lib/zope$ZVER/instance/$INSTANCE
            fi
            if [ "$clean_install" = yes ]; then
                rm -rf /var/log/zope$ZVER/$INSTANCE
                rm -rf /etc/zope$ZVER/$INSTANCE
            fi
        fi
    fi
    ;;

  *)
    echo "postinst called with unknown argument \`$1'" >&2
    exit 1
    ;;
esac
