#!/bin/sh

set -e
if [ -f /usr/share/debconf/confmodule ]; then
        . /usr/share/debconf/confmodule
fi

seen='false'
askuser() {
    question='vidalia/tor-daemon-interaction'
    db_input high $question || true
    db_go || true
    db_get $question
}

if [ "$1" = "configure" ] || [ "$1" = "reconfigure" ]; then
        if dpkg -l tor > /dev/null 2>&1; then
            # installed
            if [ -e '/var/run/tor/tor.pid' ] || [ "$1" = "reconfigure" ]; then
                # and already running
                askuser
                seen='true'
		case "$RET" in
			(nothing)
			if [ -f /etc/default/tor.vidalia ]; then
			ucf --debconf-ok --three-way /usr/share/vidalia/default.tor-on /etc/default/tor.vidalia
			fi
		;;
			(one-off) 
                    	invoke-rc.d --force tor stop
			if [ -f /etc/default/tor.vidalia ]; then
			ucf --debconf-ok --three-way /usr/share/vidalia/default.tor-on /etc/default/tor.vidalia
			fi
		;;
			(permanent)
			invoke-rc.d --force tor stop
			ucf --debconf-ok --three-way /usr/share/vidalia/default.tor-off /etc/default/tor.vidalia
		;;
		esac
            fi
        fi

        if pgrep -x tor > /dev/null 2>&1; then 
                # still running?? (e.g. chroot)
                if [ "$seen" = "false" ]; then
                        askuser
                        if [ "$RET" = "one-off" ] || [ "$RET" = "permanent" ]; then
                            echo -n "Stopping tor daemon: "
                            pkill -x tor > /dev/null && echo "tor." || echo 'Failed!'
                        fi
                fi
        fi
        db_stop
fi

#DEBHELPER#
