#!/bin/sh
# Provision a FreeBSD 15.1 host for the rChat relay (run as root).
set -eu

# Service user: no login shell, home /var/db/rchat (created below), the same
# as install.sh.
if ! pw usershow rchat >/dev/null 2>&1; then
    pw useradd rchat -c "rChat relay" -d /var/db/rchat -s /usr/sbin/nologin
fi
RCHAT_UID=$(id -u rchat)

install -d -o root -g rchat -m 0750 /usr/local/etc/rchat
install -d -o rchat -g rchat -m 0700 /var/db/rchat
install -d -o rchat -g rchat -m 0750 /var/log/rchat

# Let only the rchat user bind :443 (mac_portacl), nothing else unprivileged
# may bind a low port.
sysrc -f /boot/loader.conf mac_portacl_load="YES" >/dev/null
kldstat -q -m mac_portacl || kldload mac_portacl

cat > /etc/sysctl.conf.local <<SYSCTL
security.mac.portacl.rules=uid:${RCHAT_UID}:tcp:443
net.inet.ip.portrange.reservedlow=0
net.inet.ip.portrange.reservedhigh=0
# Hardening
kern.coredump=0
security.bsd.see_other_uids=0
security.bsd.see_other_gids=0
security.bsd.see_jail_proc=0
security.bsd.unprivileged_read_msgbuf=0
security.bsd.unprivileged_proc_debug=0
kern.randompid=1
net.inet.tcp.blackhole=2
net.inet.udp.blackhole=1
net.inet.ip.random_id=1
net.inet.tcp.drop_synfin=1
net.inet.icmp.drop_redirect=1
net.inet.ip.redirect=0
SYSCTL
sysctl -f /etc/sysctl.conf.local >/dev/null

# Logs rotated daily, 14 kept; daemon -H reopens on SIGHUP.
mkdir -p /usr/local/etc/newsyslog.conf.d
cat > /usr/local/etc/newsyslog.conf.d/rchat.conf <<NSL
/var/log/rchat/server.log rchat:rchat 640 14 * @T00 JC /var/run/rchat.pid 1
NSL

# Services the relay does not need.
sysrc sendmail_enable=NONE sendmail_submit_enable=NO sendmail_outbound_enable=NO sendmail_msp_queue_enable=NO >/dev/null
sysrc clear_tmp_enable=YES >/dev/null

# Per-relay decoy website. Needs the rchat-server binary (install.sh), the
# config and the relay identity key: the site is seeded from the key and the
# host name (RCHAT_DECOY_HOST, else [server.decoy] host / the first
# [server.acme] domain in the config, else none), so nobody without the key
# can work out the design. Every failure here only prints a note. Re-running is safe: --render-decoy writes
# only into an empty or previously rendered directory, and the config is
# edited only to add a missing `root` (an existing value is never touched).
DECOY_DIR=/var/db/rchat/decoy
CONF=/usr/local/etc/rchat/server.toml
BIN=/usr/local/bin/rchat-server
DECOY_HOST=${RCHAT_DECOY_HOST:-}
case "$DECOY_HOST" in
    *[!A-Za-z0-9.-]*) echo "RCHAT_DECOY_HOST must be a plain host name" >&2; exit 1 ;;
esac

# set_decoy_root FILE DIR: make FILE's decoy table name DIR as its root.
# Appends a [server.decoy] table when there is no decoy table or inline
# `decoy =` key; inserts `root` after an existing table header when the
# table has none; otherwise leaves the file alone and says so.
set_decoy_root() {
    f=$1 d=$2
    hdr='^[[:space:]]*\[(server\.)?decoy\][[:space:]]*(#.*)?$'
    if grep -Eq '^[[:space:]]*decoy[[:space:]]*=' "$f"; then
        echo "$f has an inline decoy setting; set root = \"$d\" in it by hand if needed"
    elif grep -Eq "$hdr" "$f"; then
        has_root=$(awk '/^[[:space:]]*\[/ { t = ($0 ~ /^[[:space:]]*\[(server\.)?decoy\][[:space:]]*(#.*)?$/) } t && /^[[:space:]]*root[[:space:]]*=/ { f = 1 } END { print f ? "yes" : "no" }' "$f")
        if [ "$has_root" = yes ]; then
            echo "$f already sets a decoy root; left as is"
        else
            tmp="$f.new.$$"
            awk -v root="$d" '{ print } !done && $0 ~ /^[[:space:]]*\[(server\.)?decoy\][[:space:]]*(#.*)?$/ { print "root = \"" root "\""; done = 1 }' "$f" > "$tmp" &&
                cat "$tmp" > "$f" && echo "set root = \"$d\" in the decoy table of $f"
            rm -f "$tmp"
        fi
    elif grep -Eq '^[[:space:]]*\[server\]' "$f"; then
        printf '\n[server.decoy]\nroot = "%s"\n' "$d" >> "$f"
        echo "added [server.decoy] root = \"$d\" to $f"
    else
        echo "add to $f:  [server.decoy]  root = \"$d\""
    fi
}

if [ -x "$BIN" ]; then
    if [ -n "$DECOY_HOST" ]; then
        su -m rchat -c "$BIN --config $CONF --render-decoy $DECOY_DIR --host $DECOY_HOST" ||
            echo "decoy not rendered (see the message above); create the config and the relay identity, then re-run" >&2
    else
        su -m rchat -c "$BIN --config $CONF --render-decoy $DECOY_DIR" ||
            echo "decoy not rendered (see the message above); create the config and the relay identity, then re-run" >&2
    fi
else
    echo "decoy not rendered: $BIN is not installed yet (run install.sh, then re-run this script)"
fi
if [ -f "$DECOY_DIR/.decoy-rendered" ] && [ -f "$CONF" ]; then
    set_decoy_root "$CONF" "$DECOY_DIR"
fi

echo "provisioned (rchat uid ${RCHAT_UID})"

# Last: the relay invite (a link and a QR code that set up rChat for this
# relay, protocol v3 Part J), when the binary, config and host are in place.
# --print-invite itself refuses, saying what to set, when the config names
# no host ([server.decoy] host, else the first [server.acme] domain).
# The invite holds the secret WebSocket path: it is printed only to a
# terminal, never into a log or a provisioning tool's captured output.
INVITE_CMD="su -m rchat -c '$BIN --config $CONF --print-invite'"
if [ ! -t 1 ]; then
    echo "to print the relay invite, run in a terminal: $INVITE_CMD"
elif [ -x "$BIN" ] && [ -f "$CONF" ]; then
    if su -m rchat -c "$BIN --config $CONF --print-invite"; then
        :
    else
        echo "no invite printed (see the message above): set host = \"your.domain.example\" under [server.decoy] in $CONF, then run: $INVITE_CMD"
    fi
else
    echo "to invite people later, set host under [server.decoy] in $CONF and run: $INVITE_CMD"
fi
