#!/bin/sh
set -e

NAME=mautrix-kakaotalk
CFGDIR=/etc/$NAME
PORT=29333
DBUSER=$NAME
DBNAME=$NAME

echo "==> building binary"
cd "$(dirname "$0")"
./build.sh

echo "==> installing binary to /usr/bin/$NAME"
if [ -f /usr/bin/$NAME ]; then
    cp /usr/bin/$NAME /usr/bin/$NAME.bak 2>/dev/null || true
fi
install -m 0755 ./$NAME /usr/bin/$NAME

echo "==> creating config dir $CFGDIR"
mkdir -p $CFGDIR
chmod 700 $CFGDIR

if [ -f $CFGDIR/config.yaml ]; then
    echo "config.yaml already exists, keeping it"
else
    echo "==> writing example config to $CFGDIR/config.yaml"
    /usr/bin/$NAME -e -c $CFGDIR/config.yaml
fi

echo "==> setting up postgres database"
if ! su postgres -c "psql -tAc \"SELECT 1 FROM pg_roles WHERE rolname='$DBUSER'\"" | grep -q 1; then
    DBPASS=$(head -c 24 /dev/urandom | base64 | tr -d '/+=' | head -c 24)
    su postgres -c "psql -c \"CREATE ROLE $DBUSER LOGIN PASSWORD '$DBPASS'\""
    echo "Generated DB password: $DBPASS"
else
    echo "role $DBUSER already exists, using configured password"
    DBPASS=$(grep -oP '(?<=postgres://'$DBUSER':)[^@]+' $CFGDIR/config.yaml || true)
fi
if ! su postgres -c "psql -tAc \"SELECT 1 FROM pg_database WHERE datname='$DBNAME'\"" | grep -q 1; then
    su postgres -c "psql -c \"CREATE DATABASE $DBNAME OWNER $DBUSER\""
fi
DBURI="postgres://$DBUSER:$DBPASS@/$DBNAME?host=/run/postgresql"
sed -i "s|^[[:space:]]*uri:.*|    uri: $DBURI|" $CFGDIR/config.yaml

echo "==> generating registration"
/usr/bin/$NAME -g -c $CFGDIR/config.yaml -r $CFGDIR/registration.yaml

echo "==> registering appservice with synapse"
if ! grep -q "$CFGDIR/registration.yaml" /etc/synapse/homeserver.yaml; then
    sed -i '/app_service_config_files:/,/^[a-z]/ { /- \/etc\/mautrix-signal\/registration.yaml/a\  - /etc/mautrix-kakaotalk/registration.yaml
}' /etc/synapse/homeserver.yaml
    echo "registered in synapse homeserver.yaml (synapse restart required)"
else
    echo "already registered"
fi

echo "==> adding rc.boot entry"
if ! grep -q "$NAME" /etc/rc.d/rc.boot; then
    cat >> /etc/rc.d/rc.boot <<EOF

log "$NAME"
if [ -d $CFGDIR ]; then
    exec /usr/bin/$NAME -c $CFGDIR/config.yaml
fi >>/var/log/$NAME.log 2>&1 &
EOF
    echo "rc.boot entry added"
else
    echo "rc.boot entry already present"
fi

echo
echo "DONE. Next steps:"
echo "  systemctl restart synapse   (or busybox init: restart synapse service)"
echo "  /usr/bin/$NAME -c $CFGDIR/config.yaml"
echo "  In Matrix: message @kakaotalkbot:marlonivo.com with: login"
