#!/bin/bash -x

mkdir -p /config/jicofo

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

OLD_JICOFO_COMPONENT_SECRET=s3cr37
if [[ "$JICOFO_COMPONENT_SECRET" == "$OLD_JICOFO_COMPONENT_SECRET" ]]; then
    echo 'FATAL ERROR: Jicofo component secret must be changed, check the README'
    exit 1
fi

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

if [ -z "$MAX_BRIDGE_PACKET_RATE" ] ; then
    export MAX_BRIDGE_PACKET_RATE=8000
else
    export MAX_BRIDGE_PACKET_RATE="$MAX_BRIDGE_PACKET_RATE"
fi

envsubst < /defaults/jicofo/sip-communicator.properties > /config/jicofo/sip-communicator.properties

cp /defaults/jicofo/logging.properties /config/jicofo

chown -R jicofo:jitsi /var/log/telemost/jicofo

chown -R jicofo:jitsi /config/jicofo

# fix bad permissions after mount layer or static resource
chown jicofo:jitsi /usr/share/jicofo

# fix certs permissions

if [ -d /config/jicofo/certs ]; then
    chmod -R u=rX,g=rX,o-rwx /config/jicofo/certs
fi
