#!/bin/sh
set -e

BRIDGE_NAME="mautrix-xmpp"
CONFIG_DIR="/etc/$BRIDGE_NAME"
DATA_DIR="/var/lib/$BRIDGE_NAME"
LOG_FILE="/var/log/$BRIDGE_NAME.log"
PORT=29335

echo "Installing $BRIDGE_NAME..."

if ! command -v mautrix-xmpp >/dev/null 2>&1; then
	echo "Error: mautrix-xmpp not found in PATH"
	exit 1
fi

mkdir -p "$CONFIG_DIR" "$DATA_DIR"

if [ ! -f "$CONFIG_DIR/config.yaml" ]; then
	mautrix-xmpp --generate-example-config > "$CONFIG_DIR/config.yaml"
	echo "Generated example config: $CONFIG_DIR/config.yaml"
	echo "Edit it before starting the bridge."
fi

if [ ! -f "$CONFIG_DIR/registration.yaml" ]; then
	cd /tmp
	mautrix-xmpp --generate-registration \
		--appservice-id "$BRIDGE_NAME" \
		--appservice-as-user-id "@${BRIDGE_NAME}bot:YOUR_DOMAIN" \
		--appservice-bot "@${BRIDGE_NAME}bot:YOUR_DOMAIN" \
		--listen-address "http://127.0.0.1:$PORT" \
		> "$CONFIG_DIR/registration.yaml"
	echo "Generated registration: $CONFIG_DIR/registration.yaml"
	echo "Add this to your Synapse homeserver.yaml:"
	echo "  app_service_config_files:"
	echo "    - '$CONFIG_DIR/registration.yaml'"
fi

echo ""
echo "Setup complete."
echo "1. Edit $CONFIG_DIR/config.yaml"
echo "2. Add registration.yaml to Synapse homeserver.yaml"
echo "3. Restart Synapse"
echo "4. Start: mautrix-xmpp -c $CONFIG_DIR/config.yaml"
