#!/bin/sh
set -e

# TODO: make a real RPM spec file and move all of this into the spec file
# <https://docs.fedoraproject.org/en-US/packaging-guidelines/Scriptlets/>

TUWUNEL_DATABASE_PATH=/var/lib/tuwunel
TUWUNEL_CONFIG_PATH=/etc/tuwunel

# Create the `tuwunel` user if it does not exist yet.
if ! getent passwd tuwunel > /dev/null ; then
  echo 'Adding system user for the tuwunel Matrix homeserver' 1>&2
  useradd --system --user-group \
    --create-home --home-dir "$TUWUNEL_DATABASE_PATH" \
    --shell "/usr/sbin/nologin" \
    tuwunel
fi

# Create the database path if it does not exist yet and fix up ownership
# and permissions for the config.
mkdir -v -p "$TUWUNEL_DATABASE_PATH"

# symlink the previous location for compatibility if it does not exist yet.
if ! test -L "/var/lib/matrix-conduit" ; then
    ln -s -v "$TUWUNEL_DATABASE_PATH" "/var/lib/matrix-conduit"
fi

if ! test -L "/var/lib/conduwuit" ; then
    ln -s -v "$TUWUNEL_DATABASE_PATH" "/var/lib/conduwuit"
fi

chown -v tuwunel:tuwunel -R "$TUWUNEL_DATABASE_PATH"
chown -v tuwunel:tuwunel -R "$TUWUNEL_CONFIG_PATH"

chmod -v 740 "$TUWUNEL_DATABASE_PATH"

echo ''
echo 'Make sure you edit the example config at /etc/tuwunel/tuwunel.toml before starting!'
echo 'To start the server, run: systemctl start tuwunel.service'
echo ''
