#!/bin/sh
set -e

. /usr/share/debconf/confmodule

CONDUIT_CONFIG_PATH=/etc/matrix-conduit
CONDUIT_CONFIG_FILE="$CONDUIT_CONFIG_PATH/debian"
CONDUIT_DATABASE_PATH=/var/lib/matrix-conduit

case "$1" in
  configure)
    # Create the `_matrix-conduit` user if it does not exist yet.
    if ! getent passwd _matrix-conduit > /dev/null ; then
      echo 'Adding system user for the Conduit Matrix homeserver' 1>&2
      adduser --system --group --quiet \
        --home $CONDUIT_DATABASE_PATH \
        --disabled-login \
        --force-badname \
        _matrix-conduit
    fi

    # Create the database path if it does not exist yet.
    if [ ! -d "$CONDUIT_DATABASE_PATH" ]; then
      mkdir -p "$CONDUIT_DATABASE_PATH"
      chown _matrix-conduit "$CONDUIT_DATABASE_PATH"
    fi

    # Write the debconf values in the config.
    db_get matrix-conduit/hostname
    ROCKET_SERVER_NAME="$RET"
    db_get matrix-conduit/address
    ROCKET_ADDRESS="$RET"
    db_get matrix-conduit/port
    ROCKET_PORT="$RET"
    cat >"$CONDUIT_CONFIG_FILE" << EOF
# Conduit homeserver Debian configuration
#
# Conduit is an application based on the Rocket web framework.
# Configuration of Conduit happens via Debconf (of which the resulting config
# is in this file) and optionally by uncommenting and tweaking the variables in
# /etc/matrix-conduit/local.

# THIS FILE IS GENERATED BY DEBCONF AND WILL BE OVERRIDDEN!
#
# Please make changes by running:
#
# \$ dpkg-reconfigure matrix-conduit
#
# or by providing overriding changes in /etc/matrix-conduit/local.

# The server (host)name of the Matrix homeserver.
#
# This is the hostname the homeserver will be reachable at via a client.
ROCKET_SERVER_NAME="$ROCKET_SERVER_NAME"

# The address the Matrix homeserver listens on.
#
# By default the server listens on address 0.0.0.0. Change this to 127.0.0.1 to
# only listen on the localhost when using a reverse proxy.
ROCKET_ADDRESS="$ROCKET_ADDRESS"

# The port of the Matrix homeserver.
#
# This port is could be any available port if accessed by a reverse proxy.
# By default the server listens on port 8000.
ROCKET_PORT="$ROCKET_PORT"

# THIS FILE IS GENERATED BY DEBCONF AND WILL BE OVERRIDDEN!
EOF
    ;;
esac

#DEBHELPER#