Merge pull request #52 from apache/postrm_remove_databases

Add extra protection to databases during package purge
diff --git a/debian/couchdb.postrm b/debian/couchdb.postrm
index c844e43..49ae092 100644
--- a/debian/couchdb.postrm
+++ b/debian/couchdb.postrm
@@ -19,21 +19,36 @@
         if test -d "/opt/couchdb/etc"; then
             rm -rf "/opt/couchdb/etc"
         fi
-        if test -d "/var/lib/couchdb"; then
-            rm -rf "/var/lib/couchdb"
-        fi
         if test -d "/var/log/couchdb"; then
             rm -rf "/var/log/couchdb"
         fi
+
+        db_input high couchdb/postrm_remove_databases || true
+        db_go || true
+        db_get couchdb/postrm_remove_databases || true
+
+        if [ "$RET" = "true" ]; then
+            if test -d "/var/lib/couchdb"; then
+                rm -rf "/var/lib/couchdb"
+            fi
+
+            # If we didn't delete the data, we should
+            # keep the uid and gid too.
+            if getent passwd couchdb > /dev/null; then
+                deluser couchdb >/dev/null 2>&1
+            fi
+            if getent group couchdb > /dev/null; then
+                delgroup couchdb >/dev/null 2>&1
+            fi
+
+            # The node name is embedded in the _dbs
+            # documents, so we must not reset it if
+            # we preserved the data.
+            db_reset couchdb/nodename
+        fi
+
         pkill -u couchdb >/dev/null 2>&1 || true
-        if getent passwd couchdb > /dev/null; then
-            deluser couchdb >/dev/null 2>&1
-        fi
-        if getent group couchdb > /dev/null; then
-            delgroup couchdb >/dev/null 2>&1
-        fi
         db_reset couchdb/mode
-        db_reset couchdb/nodename
         db_reset couchdb/cookie
         db_reset couchdb/adminpass
         db_reset couchdb/adminpass_again
diff --git a/debian/couchdb.templates b/debian/couchdb.templates
index 0fc5acd..6fb7cfa 100644
--- a/debian/couchdb.templates
+++ b/debian/couchdb.templates
@@ -94,3 +94,11 @@
  /var/lib/couchdb directory. These need migration to be used in
  CouchDB 2.x and forward. Use the `couchup' utility to assist in
  the migration process.
+
+Template: couchdb/postrm_remove_databases
+Type: boolean
+Default: false
+_Description: Remove all CouchDB databases?
+ The /var/lib/couchdb directory containing all CouchDB databases will
+ be removed. This will also clear the stored node name for this machine,
+ and remove the couchdb user and group.