#!/bin/sh
# postinst script for torch-agent
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package

USER="torch"
GROUP="debian-tor"

TORRC="/etc/tor/torrc"

configure_tor_controller() {

    TORRC_CHANGED=0

    if ! grep -q "^ControlPort [0-9]\+" $TORRC; then
        sed -i '/^#ControlPort 9051/s/^#//' $TORRC
        TORRC_CHANGED=1
	fi

    if ! grep -q "^CookieAuthentication 1" $TORRC; then
        sed -i '/^#CookieAuthentication 1/s/^#//' $TORRC
        TORRC_CHANGED=1
	fi

    if ! grep -q "^CookieAuthFileGroupReadable 1" $TORRC; then
        echo "CookieAuthFileGroupReadable 1" >> $TORRC
        TORRC_CHANGED=1
	fi
	
	if [ $TORRC_CHANGED -eq 1 ]; then
	    if [ -d "/run/systemd/system" ]; then
                systemctl reload tor
	    fi
	fi
}

case "$1" in
    configure)

    if ! getent passwd $USER >/dev/null ; then
        useradd -r -g $GROUP $USER
    fi

    sudo -H pip3 install 'paho-mqtt>=1.5.1'

    chown $USER /etc/torch
    chown $USER /etc/torch/torch.conf

    configure_tor_controller
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

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

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
