#!/bin/bash -x

PROSODY_CFG="/config/prosody/prosody.cfg.lua"

if [[ ! -d /config/prosody/data ]]; then
    mkdir -pm 750 /config/prosody/data
fi

if [[ "$(stat -c %U /config/prosody)" != "prosody" ]]; then
    chown -R prosody /config/prosody
fi

if [[ "$(stat -c %U /prosody-plugins)" != "prosody" ]]; then
    chown -R prosody /prosody-plugins
fi

if [[ "$(stat -c %U /prosody-plugins-custom)" != "prosody" ]]; then
    chown -R prosody /prosody-plugins-custom
fi

JICOFO_AUTH_USER=focus
export XMPP_AUTH_DOMAIN=auth.$XMPP_DOMAIN
JVB_AUTH_USER=jvb

    cp -r /defaults/prosody/* /config/prosody
    envsubst < /defaults/prosody/prosody.cfg.lua > $PROSODY_CFG
    envsubst < /defaults/prosody/conf.d/jitsi-meet.cfg.lua > /config/prosody/conf.d/jitsi-meet.cfg.lua

    if [[ -z $JICOFO_COMPONENT_SECRET || -z $JICOFO_AUTH_PASSWORD ]]; then
        echo 'FATAL ERROR: Jicofo component secret and auth password must be set'
        exit 1
    fi

    prosodyctl --config $PROSODY_CFG register $JICOFO_AUTH_USER $XMPP_AUTH_DOMAIN $JICOFO_AUTH_PASSWORD

    if [[ -z $JVB_AUTH_PASSWORD ]]; then
        echo 'FATAL ERROR: JVB auth password must be set'
        exit 1
    fi

    OLD_JVB_AUTH_PASSWORD=passw0rd
    if [[ "$JVB_AUTH_PASSWORD" == "$OLD_JVB_AUTH_PASSWORD" ]]; then
        echo 'FATAL ERROR: JVB auth password must be changed, check the README'
        exit 1
    fi

    prosodyctl --config $PROSODY_CFG register $JVB_AUTH_USER $XMPP_AUTH_DOMAIN $JVB_AUTH_PASSWORD

    if [[ -z $AUTH_USER || -z $AUTH_PASSWORD ]]; then
        echo 'FATAL ERROR: auth password must be set'
        exit 1
    fi

    prosodyctl --config $PROSODY_CFG register $AUTH_USER $XMPP_DOMAIN $AUTH_PASSWORD


mkdir -p /config/prosody/certs

if [[ ! -f /config/prosody/certs/$XMPP_DOMAIN.crt ]]; then
    # echo for using all default values
    echo | prosodyctl --config $PROSODY_CFG cert generate $XMPP_DOMAIN
fi

if [[ ! -f /config/prosody/certs/$XMPP_AUTH_DOMAIN.crt ]]; then
    # echo for using all default values
    echo | prosodyctl --config $PROSODY_CFG cert generate $XMPP_AUTH_DOMAIN
fi

# certs will be created in /config/data
mv /config/prosody/data/*.{crt,key} /config/prosody/certs/ || true
rm -f /config/prosody/data/*.cnf
