#!/bin/bash
# postinst script for jitsi-videobridge

set -e

case "$1" in
    configure)

        CONFIG="/etc/jitsi/videobridge/config"

        # we don't want to regenerate config on upgrade
        OLDCONFIG="false"
        # migrate any old config found
        if [ -f "/etc/default/jitsi-videobridge" ]; then
            mv /etc/default/jitsi-videobridge $CONFIG
        fi

        if [ -f $CONFIG ]; then
            . $CONFIG
            if [ -n "$JVB_HOSTNAME" ] && [ -n "$JVB_SECRET" ]; then
                OLDCONFIG="true"
            fi
        fi

        # debconf hostname question
        . /usr/share/debconf/confmodule

        # the default vars
        db_get jitsi-videobridge/jvb-hostname
        JVB_HOSTNAME_IN=$(echo "$RET" | xargs echo -n)

        # generate config on new install or when we are reconfiguring
        # and all install is different than current one
        if [ "$OLDCONFIG" = "false" ] || [ "$JVB_HOSTNAME" != "$JVB_HOSTNAME_IN" ]; then

            JVB_HOSTNAME="$JVB_HOSTNAME_IN"
            if [ "$OLDCONFIG" = "false" ]; then
                # 8-chars random secret, alternative to pwgen 8
                JVB_SECRET=`head -c 8 /dev/urandom | tr '\0-\377' 'a-zA-Z0-9a-zA-Z0-9a-zA-Z0-9a-zA-Z0-9@@@@####'`
            fi
        fi

        # Store it, so we can use it if xmpp server is on same machine
        # we are currently doing this on every upgrade in order to be able to successfully upgrade
        # from old packages, otherwise we can do it only when secret is first time generated
        db_set jitsi-videobridge/jvbsecret $JVB_SECRET

        # and we're done with debconf
        db_stop

        OLD_JITSI_CONFIG="/usr/share/jitsi-videobridge/.sip-communicator/sip-communicator.properties"
        NEW_JITSI_CONFIG="/etc/jitsi/videobridge/sip-communicator.properties"
        HOCON_CONFIG="/etc/jitsi/videobridge/jvb.conf"

        if [ -f $OLD_JITSI_CONFIG ]; then
            mv $OLD_JITSI_CONFIG $NEW_JITSI_CONFIG
            echo "# Config has moved to /etc/jitsi/videobridge/
# do not edit this file as it is not used" > ${OLD_JITSI_CONFIG}.old
        elif [ ! -f $NEW_JITSI_CONFIG ]; then
            # if sip-communicator.properties file is missing create it
            # as jvb will search for it and if cannot create it will fail starting
            touch $NEW_JITSI_CONFIG
        fi

        # let's check whether there is a setting in the $CONFIG
        # for home folder and logging props file, if missing add it
        if ! grep -q "JAVA_SYS_PROPS" "$CONFIG"; then
            echo >> $CONFIG
            echo '# adds java system props that are passed to jvb (default are for home and logging config file)' >> $CONFIG
            echo "JAVA_SYS_PROPS=\"-Dnet.java.sip.communicator.SC_HOME_DIR_LOCATION=/etc/jitsi\
 -Dnet.java.sip.communicator.SC_HOME_DIR_NAME=videobridge\
 -Dnet.java.sip.communicator.SC_LOG_DIR_LOCATION=/var/log/jitsi\
 -Djava.util.logging.config.file=/etc/jitsi/videobridge/logging.properties\"" >> $CONFIG
        fi

        # Updates config so new and old installs will start using the new config file
        if ! grep -q "\-Dconfig.file" "$CONFIG"; then
            sed -i 's|JAVA_SYS_PROPS="|JAVA_SYS_PROPS="-Dconfig.file='"$HOCON_CONFIG"' |g' $CONFIG
        fi

        # unused old parameter, systemd unit files does not resolve bash variables,
        # and this breaks startup script
        sed -i 's/\$JVB_EXTRA_JVM_PARAMS//g' $CONFIG

        if ! grep -q "org.ice4j.ice.harvest.STUN_MAPPING_HARVESTER_ADDRESSES" "$NEW_JITSI_CONFIG" \
          && ! grep -q "org.ice4j.ice.harvest.NAT_HARVESTER_PUBLIC_ADDRESS" "$NEW_JITSI_CONFIG" ;then
            echo "org.ice4j.ice.harvest.DISABLE_AWS_HARVESTER=true" >> $NEW_JITSI_CONFIG
            echo "org.ice4j.ice.harvest.STUN_MAPPING_HARVESTER_ADDRESSES=meet-jit-si-turnrelay.jitsi.net:443" >> $NEW_JITSI_CONFIG
        fi

        if ! grep -q "org.jitsi.videobridge.xmpp.user.shard.MUC_JIDS" "$NEW_JITSI_CONFIG" ;then
            echo "org.jitsi.videobridge.ENABLE_STATISTICS=true" >> $NEW_JITSI_CONFIG
            echo "org.jitsi.videobridge.STATISTICS_TRANSPORT=muc" >> $NEW_JITSI_CONFIG
            echo "org.jitsi.videobridge.xmpp.user.shard.HOSTNAME=localhost" >> $NEW_JITSI_CONFIG
            echo "org.jitsi.videobridge.xmpp.user.shard.DOMAIN=auth.$JVB_HOSTNAME" >> $NEW_JITSI_CONFIG
            echo "org.jitsi.videobridge.xmpp.user.shard.USERNAME=jvb" >> $NEW_JITSI_CONFIG
            echo "org.jitsi.videobridge.xmpp.user.shard.PASSWORD=$JVB_SECRET" >> $NEW_JITSI_CONFIG
            echo "org.jitsi.videobridge.xmpp.user.shard.MUC_JIDS=JvbBrewery@internal.auth.$JVB_HOSTNAME" >> $NEW_JITSI_CONFIG
            echo "org.jitsi.videobridge.xmpp.user.shard.MUC_NICKNAME=$(uuidgen)" >> $NEW_JITSI_CONFIG
        fi

        if [ ! -f $HOCON_CONFIG ]; then
            echo "Generating an empty hocon config"
            echo "videobridge {
    http-servers {
        public {
            port = 9090
        }
    }
    websockets {
        enabled = true
        domain = \"$JVB_HOSTNAME:443\"
        tls = true
    }
}" >> $HOCON_CONFIG
        fi

        # The REST API is disabled by default. It it was previously enabled via --apis, enable it in jvb.conf
        if grep -v '^\s*#' /etc/jitsi/videobridge/config | grep -- '--apis=' | grep -i rest >/dev/null 2>&1 ;then
            if ! hocon -f $HOCON_CONFIG get "videobridge.apis.rest.enabled" > /dev/null 2>&1 ;then
                hocon -f $HOCON_CONFIG set "videobridge.apis.rest.enabled" "true"
            fi
            # Remove it from /etc/jitsi/videobridge/config to prevent it perpetually updating jvb.conf
            sed -i 's/.*--apis.*//' $CONFIG
        fi

        # we don't want to start the daemon as root
        if ! getent group jitsi > /dev/null ; then
            groupadd jitsi
        fi
        if ! getent passwd jvb > /dev/null ; then
            useradd -r -g jitsi --shell /bin/bash --create-home -d /usr/share/jitsi-videobridge jvb
        fi
        if ! groups jvb | grep '\bjitsi\b' > /dev/null ; then
            usermod -g jitsi jvb
        fi

        mkdir -p /usr/share/jitsi-videobridge

        # we claim the home folder of jvb in case it is owned by someone else
        OWNER=$(stat -c '%U' /usr/share/jitsi-videobridge)
        GROUP=$(stat -c '%G' /usr/share/jitsi-videobridge)
        if ! dpkg-statoverride --list /usr/share/jitsi-videobridge/* >/dev/null && [ "$OWNER:$GROUP" != "jvb:jitsi" ]; then
            chown -R jvb:jitsi /usr/share/jitsi-videobridge
            OWNER=jvb
            GROUP=jitsi
        fi

        CONFIG_DIR=$(dirname $CONFIG)
        if ! dpkg-statoverride --list "$CONFIG_DIR" >/dev/null; then
            chown -R jvb:jitsi "$CONFIG_DIR"
            chmod 750 "$CONFIG_DIR"
        fi

        # die logz
        if [ ! -d /var/log/jitsi ]; then
            mkdir -p /var/log/jitsi
        fi
        chown $OWNER:$GROUP /var/log/jitsi
        chmod 770 /var/log/jitsi
        ls /var/log/jitsi/jvb* 1>/dev/null 2>&1 && chown -f -R $OWNER:$GROUP /var/log/jitsi/jvb*
        ls /var/log/jitsi/jvb* 1>/dev/null 2>&1 && chmod -f -R 640 /var/log/jitsi/jvb*

        # ensure videobridge is not running - it will be started at the end
        if [ -d /run/systemd/system ]; then
            systemctl stop jitsi-videobridge2.service >/dev/null || true
        fi

        # clean up old jvb group
        if getent group jvb > /dev/null; then
            groupdel jvb
        fi

        # load the UDP buffer sizes required by the JVB. As reported in
        # https://github.com/jitsi/jitsi-videobridge/issues/461
        # OpenVZ containers do not typically allow permission to modify the
        # kernel with sysctl config values.
        sysctl --system || true

    ;;

    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
