#!/bin/bash
#
# Jitsi Service

PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
. /etc/federated
get_appvars

config_jitsi() {
  echo -ne "* Configuring jitsi container.."

  if [ ! -d "/federated/apps/jitsi" ]; then
     mkdir -p /federated/apps/jitsi
#    mkdir -p /federated/apps/jitsi/data/config/keys &> /dev/null
#    cp -rf /federated/apps/dns/data/etc/letsencrypt/archive/$DOMAIN/*.pem apps/jitsi/data/config/keys
#    mv /federated/apps/jitsi/data/config/keys/fullchain1.pem apps/jitsi/data/config/keys/cert.crt
#    mv /federated/apps/jitsi/data/config/keys/privkey1.pem apps/jitsi/data/config/keys/cert.key
#    chmod 644 /federated/apps/jitsi/data/config/keys/*.pem
  fi

  grep -q JITSI_SCALE /etc/federated && sed -i -e '/JITSI_SCALE/d' /etc/federated
  if [ -n "$JITSI_SCALE" ]; then
    cat >>/etc/federated <<EOF
# JITSI_SCALE: not set = use local jvb, client = jitsi only, server = jvb only
JITSI_SCALE=$JITSI_SCALE
EOF
  fi

# Extract Jitsi's gen-password.sh into /federated/apps/jitsi
install -c -m 755 /federated/lib/files/jitsi/gen-passwords.sh /federated/apps/jitsi/

[ "$JITSI_SCALE" = "server" ] && install -c -m 755 /federated/lib/files/jitsi/restart-when-idle.sh /federated/apps/jitsi/

# Create docker compose file
cat > /federated/apps/jitsi/docker-compose.yml <<EOF
services:
EOF

if [ "$JITSI_SCALE" != "server" ]; then
	cat >> /federated/apps/jitsi/docker-compose.yml <<EOF
    # Frontend
    web:
        image: jitsi/web:\${JITSI_IMAGE_VERSION:-$(current_version jitsi)}
        restart: \${RESTART_POLICY:-unless-stopped}
        ports:
          - '\${HTTP_PORT}:80'
          - '\${HTTPS_PORT}:443'
        volumes:
            - \${CONFIG}/web:/config:Z
            - \${CONFIG}/web/crontabs:/var/spool/cron/crontabs:Z
            - \${CONFIG}/transcripts:/usr/share/jitsi-meet/transcripts:Z
            - ./data/config/keys:/config/keys:Z
        labels:
            - "traefik.enable=true"
            - "traefik.http.routers.jitsi.rule=Host(\`jitsi.$DOMAIN\`)"
            - "traefik.http.routers.jitsi.entrypoints=websecure"
            - "traefik.http.routers.jitsi.tls.certresolver=letsencrypt"
        environment:
            - AMPLITUDE_ID
            - ANALYTICS_SCRIPT_URLS
            - ANALYTICS_WHITELISTED_EVENTS
            - AUDIO_QUALITY_OPUS_BITRATE
            - BRANDING_DATA_URL
            - CALLSTATS_CUSTOM_SCRIPT_URL
            - CALLSTATS_ID
            - CALLSTATS_SECRET
            - CHROME_EXTENSION_BANNER_JSON
            - CONFCODE_URL
            - CONFIG_EXTERNAL_CONNECT
            - DEFAULT_LANGUAGE
            - DEPLOYMENTINFO_ENVIRONMENT
            - DEPLOYMENTINFO_ENVIRONMENT_TYPE
            - DEPLOYMENTINFO_REGION
            - DEPLOYMENTINFO_SHARD
            - DEPLOYMENTINFO_USERREGION
            - DESKTOP_SHARING_FRAMERATE_MIN
            - DESKTOP_SHARING_FRAMERATE_MAX
            - DIALIN_NUMBERS_URL
            - DIALOUT_AUTH_URL
            - DIALOUT_CODES_URL
            - DISABLE_AUDIO_LEVELS
            - DISABLE_DEEP_LINKING
            - DISABLE_GRANT_MODERATOR
            - DISABLE_HTTPS
            - DISABLE_KICKOUT
            - DISABLE_LOCAL_RECORDING
            - DISABLE_POLLS
            - DISABLE_PRIVATE_CHAT
            - DISABLE_PROFILE
            - DISABLE_REACTIONS
            - DISABLE_REMOTE_VIDEO_MENU
            - DROPBOX_APPKEY
            - DROPBOX_REDIRECT_URI
            - DYNAMIC_BRANDING_URL
            - ENABLE_AUDIO_PROCESSING
            - ENABLE_AUTH
            - ENABLE_BREAKOUT_ROOMS
            - ENABLE_CALENDAR
            - ENABLE_COLIBRI_WEBSOCKET
            - ENABLE_E2EPING
            - ENABLE_FILE_RECORDING_SHARING
            - ENABLE_GUESTS
            - ENABLE_HSTS
            - ENABLE_HTTP_REDIRECT
            - ENABLE_IPV6
            - ENABLE_LETSENCRYPT
            - ENABLE_LIPSYNC
            - ENABLE_NO_AUDIO_DETECTION
            - ENABLE_NOISY_MIC_DETECTION
            - ENABLE_OCTO
            - ENABLE_OPUS_RED
            - ENABLE_PREJOIN_PAGE
            - ENABLE_P2P
            - ENABLE_WELCOME_PAGE
            - ENABLE_CLOSE_PAGE
            - ENABLE_LIVESTREAMING
            - ENABLE_LOCAL_RECORDING_NOTIFY_ALL_PARTICIPANT
            - ENABLE_LOCAL_RECORDING_SELF_START
            - ENABLE_RECORDING
            - ENABLE_REMB
            - ENABLE_REQUIRE_DISPLAY_NAME
            - ENABLE_SERVICE_RECORDING
            - ENABLE_SIMULCAST
            - ENABLE_STATS_ID
            - ENABLE_STEREO
            - ENABLE_SUBDOMAINS
            - ENABLE_TALK_WHILE_MUTED
            - ENABLE_TCC
            - ENABLE_TRANSCRIPTIONS
            - ENABLE_XMPP_WEBSOCKET
            - ENABLE_JAAS_COMPONENTS
            - ENABLE_MULTI_STREAM
            - ETHERPAD_PUBLIC_URL
            - ETHERPAD_URL_BASE
            - E2EPING_NUM_REQUESTS
            - E2EPING_MAX_CONFERENCE_SIZE
            - E2EPING_MAX_MESSAGE_PER_SECOND
            - GOOGLE_ANALYTICS_ID
            - GOOGLE_API_APP_CLIENT_ID
            - HIDE_PREMEETING_BUTTONS
            - HIDE_PREJOIN_DISPLAY_NAME
            - HIDE_PREJOIN_EXTRA_BUTTONS
            - INVITE_SERVICE_URL
            - JICOFO_AUTH_USER
            - LETSENCRYPT_DOMAIN
            - LETSENCRYPT_EMAIL
            - LETSENCRYPT_USE_STAGING
            - MATOMO_ENDPOINT
            - MATOMO_SITE_ID
            - MICROSOFT_API_APP_CLIENT_ID
            - NGINX_RESOLVER
            - NGINX_WORKER_PROCESSES
            - NGINX_WORKER_CONNECTIONS
            - PEOPLE_SEARCH_URL
            - PUBLIC_URL
            - P2P_PREFERRED_CODEC
            - RESOLUTION
            - RESOLUTION_MIN
            - RESOLUTION_WIDTH
            - RESOLUTION_WIDTH_MIN
            - START_AUDIO_MUTED
            - START_AUDIO_ONLY
            - START_BITRATE
            - START_SILENT
            - START_WITH_AUDIO_MUTED
            - START_VIDEO_MUTED
            - START_WITH_VIDEO_MUTED
            - TESTING_CAP_SCREENSHARE_BITRATE
            - TESTING_OCTO_PROBABILITY
            - TOKEN_AUTH_URL
            - TOOLBAR_BUTTONS
            - TZ
            - VIDEOQUALITY_BITRATE_H264_LOW
            - VIDEOQUALITY_BITRATE_H264_STANDARD
            - VIDEOQUALITY_BITRATE_H264_HIGH
            - VIDEOQUALITY_BITRATE_VP8_LOW
            - VIDEOQUALITY_BITRATE_VP8_STANDARD
            - VIDEOQUALITY_BITRATE_VP8_HIGH
            - VIDEOQUALITY_BITRATE_VP9_LOW
            - VIDEOQUALITY_BITRATE_VP9_STANDARD
            - VIDEOQUALITY_BITRATE_VP9_HIGH
            - VIDEOQUALITY_ENFORCE_PREFERRED_CODEC
            - VIDEOQUALITY_PREFERRED_CODEC
            - XMPP_AUTH_DOMAIN
            - XMPP_BOSH_URL_BASE
            - XMPP_DOMAIN
            - XMPP_GUEST_DOMAIN
            - XMPP_MUC_DOMAIN
            - XMPP_RECORDER_DOMAIN
            - XMPP_PORT
        networks:
          core:
            ipv4_address: 192.168.0.25

    # XMPP server
    prosody:
        image: jitsi/prosody:\${JITSI_IMAGE_VERSION:-$(current_version jitsi)}
        restart: \${RESTART_POLICY:-unless-stopped}
        expose:
            - '\${XMPP_PORT:-5222}'
            - '5347'
            - '5280'
EOF

	if [ "$JITSI_SCALE" = "client" ]; then
		cat >> /federated/apps/jitsi/docker-compose.yml <<EOF
        ports:
            - '5222:5222'
            - '5347:5347'
            - '5280:5280'
EOF
	fi


	cat >> /federated/apps/jitsi/docker-compose.yml <<EOF
        volumes:
            - \${CONFIG}/prosody/config:/config:Z
            - \${CONFIG}/prosody/prosody-plugins-custom:/prosody-plugins-custom:Z
        environment:
            - AUTH_TYPE
            - DISABLE_POLLS
            - ENABLE_AUTH
            - ENABLE_AV_MODERATION
            - ENABLE_BREAKOUT_ROOMS
            - ENABLE_END_CONFERENCE
            - ENABLE_GUESTS
            - ENABLE_IPV6
            - ENABLE_LOBBY
            - ENABLE_RECORDING
            - ENABLE_XMPP_WEBSOCKET
            - ENABLE_JAAS_COMPONENTS
            - GC_TYPE
            - GC_INC_TH
            - GC_INC_SPEED
            - GC_INC_STEP_SIZE
            - GC_GEN_MIN_TH
            - GC_GEN_MAX_TH
            - GLOBAL_CONFIG
            - GLOBAL_MODULES
            - JIBRI_RECORDER_USER
            - JIBRI_RECORDER_PASSWORD
            - JIBRI_XMPP_USER
            - JIBRI_XMPP_PASSWORD
            - JICOFO_AUTH_USER
            - JICOFO_AUTH_PASSWORD
            - JICOFO_COMPONENT_SECRET
            - JIGASI_XMPP_USER
            - JIGASI_XMPP_PASSWORD
            - JVB_AUTH_USER
            - JVB_AUTH_PASSWORD
            - JWT_APP_ID
            - JWT_APP_SECRET
            - JWT_ACCEPTED_ISSUERS
            - JWT_ACCEPTED_AUDIENCES
            - JWT_ASAP_KEYSERVER
            - JWT_ALLOW_EMPTY
            - JWT_AUTH_TYPE
            - JWT_ENABLE_DOMAIN_VERIFICATION
            - JWT_TOKEN_AUTH_MODULE
            - MATRIX_UVS_URL
            - MATRIX_UVS_ISSUER
            - MATRIX_UVS_AUTH_TOKEN
            - MATRIX_UVS_SYNC_POWER_LEVELS
            - LOG_LEVEL
            - LDAP_AUTH_METHOD
            - LDAP_BASE
            - LDAP_BINDDN
            - LDAP_BINDPW
            - LDAP_FILTER
            - LDAP_VERSION
            - LDAP_TLS_CIPHERS
            - LDAP_TLS_CHECK_PEER
            - LDAP_TLS_CACERT_FILE
            - LDAP_TLS_CACERT_DIR
            - LDAP_START_TLS
            - LDAP_URL
            - LDAP_USE_TLS
            - MAX_PARTICIPANTS
            - PROSODY_RESERVATION_ENABLED
            - PROSODY_RESERVATION_REST_BASE_URL
            - PUBLIC_URL
            - TURN_CREDENTIALS
            - TURN_HOST
            - TURNS_HOST
            - TURN_PORT
            - TURNS_PORT
            - TZ
            - XMPP_DOMAIN
            - XMPP_AUTH_DOMAIN
            - XMPP_GUEST_DOMAIN
            - XMPP_MUC_DOMAIN
            - XMPP_INTERNAL_MUC_DOMAIN
            - XMPP_MODULES
            - XMPP_MUC_MODULES
            - XMPP_MUC_CONFIGURATION
            - XMPP_INTERNAL_MUC_MODULES
            - XMPP_RECORDER_DOMAIN
            - XMPP_PORT
        networks:
          core:
            ipv4_address: 192.168.0.26
            aliases:
              - xmpp.meet.jitsi
              - xmpp.$DOMAIN

    # Focus component
    jicofo:
        image: jitsi/jicofo:\${JITSI_IMAGE_VERSION:-$(current_version jitsi)}
        restart: \${RESTART_POLICY:-unless-stopped}
        volumes:
            - \${CONFIG}/jicofo:/config:Z
        environment:
            - AUTH_TYPE
            - BRIDGE_AVG_PARTICIPANT_STRESS
            - BRIDGE_STRESS_THRESHOLD
            - ENABLE_AUTH
            - ENABLE_AUTO_OWNER
            - ENABLE_CODEC_VP8
            - ENABLE_CODEC_VP9
            - ENABLE_CODEC_H264
            - ENABLE_OCTO
            - ENABLE_RECORDING
            - ENABLE_SCTP
            - ENABLE_AUTO_LOGIN
            - JICOFO_AUTH_USER
            - JICOFO_AUTH_PASSWORD
            - JICOFO_ENABLE_BRIDGE_HEALTH_CHECKS
            - JICOFO_CONF_INITIAL_PARTICIPANT_WAIT_TIMEOUT
            - JICOFO_CONF_SINGLE_PARTICIPANT_TIMEOUT
            - JICOFO_ENABLE_HEALTH_CHECKS
            - JICOFO_SHORT_ID
            - JIBRI_BREWERY_MUC
            - JIBRI_REQUEST_RETRIES
            - JIBRI_PENDING_TIMEOUT
            - JIGASI_BREWERY_MUC
            - JIGASI_SIP_URI
            - JVB_BREWERY_MUC
            - MAX_BRIDGE_PARTICIPANTS
            - OCTO_BRIDGE_SELECTION_STRATEGY
            - SENTRY_DSN="\${JICOFO_SENTRY_DSN:-0}"
            - SENTRY_ENVIRONMENT
            - SENTRY_RELEASE
            - TZ
            - XMPP_DOMAIN
            - XMPP_AUTH_DOMAIN
            - XMPP_INTERNAL_MUC_DOMAIN
            - XMPP_MUC_DOMAIN
            - XMPP_RECORDER_DOMAIN
            - XMPP_SERVER
            - XMPP_PORT
        depends_on:
            - prosody
        networks:
          core:
            ipv4_address: 192.168.0.27

EOF
fi
if [ "$JITSI_SCALE" != "client" ]; then
	cat >> /federated/apps/jitsi/docker-compose.yml <<EOF
    # Video bridge
    jvb:
        image: jitsi/jvb:\${JITSI_IMAGE_VERSION:-$(current_version jitsi)}
        restart: \${RESTART_POLICY:-unless-stopped}
        ports:
            - '\${JVB_PORT:-10000}:\${JVB_PORT:-10000}/udp'
            - '127.0.0.1:\${JVB_COLIBRI_PORT:-9090}:9090'
EOF
	if [ "$JITSI_SCALE" = "server" ]; then
		# 8080 is the PRIVATE interface, giving access to
		# endpoints like /colibri/stats - useful for JVB
		# servers to see whether or not there are any
		# active connections
		cat >> /federated/apps/jitsi/docker-compose.yml <<EOF
            - '127.0.0.1:8080:8080'
EOF
	fi
	cat >> /federated/apps/jitsi/docker-compose.yml <<EOF
        volumes:
            - \${CONFIG}/jvb:/config:Z
        environment:
            - DOCKER_HOST_ADDRESS
            - ENABLE_COLIBRI_WEBSOCKET
            - ENABLE_OCTO
            - ENABLE_MULTI_STREAM
            - JVB_ADVERTISE_IPS
            - JVB_ADVERTISE_PRIVATE_CANDIDATES
            - JVB_AUTH_USER
            - JVB_AUTH_PASSWORD
            - JVB_BREWERY_MUC
            - JVB_DISABLE_STUN
            - JVB_PORT
            - JVB_MUC_NICKNAME
            - JVB_STUN_SERVERS
            - JVB_OCTO_BIND_ADDRESS
            - JVB_OCTO_REGION
            - JVB_OCTO_RELAY_ID
            - JVB_WS_DOMAIN
            - JVB_WS_SERVER_ID
            - PUBLIC_URL
            - SENTRY_DSN="\${JVB_SENTRY_DSN:-0}"
            - SENTRY_ENVIRONMENT
            - SENTRY_RELEASE
            - COLIBRI_REST_ENABLED
            - SHUTDOWN_REST_ENABLED
            - TZ
            - XMPP_AUTH_DOMAIN
            - XMPP_INTERNAL_MUC_DOMAIN
            - XMPP_SERVER
            - XMPP_PORT
EOF
	if [ "$JITSI_SCALE" != "server" ]; then
		cat >> /federated/apps/jitsi/docker-compose.yml <<EOF
        depends_on:
            - prosody
EOF
	fi

	cat >> /federated/apps/jitsi/docker-compose.yml <<EOF
        networks:
          core:
            ipv4_address: 192.168.0.28
EOF
fi

cat >> /federated/apps/jitsi/docker-compose.yml <<EOF

networks:
  core:
    external: true
EOF

[[ "${PLUS}" = "true" ]] && sed -i "s/letsencrypt/httpresolver/g" /federated/apps/jitsi/docker-compose.yml

# Create Jitsi .env file
cat > /federated/apps/jitsi/.env <<EOF
# shellcheck disable=SC2034
################################################################################
################################################################################
# Welcome to the Jitsi Meet Docker setup!
#
# This sample .env file contains some basic options to get you started.
# The full options reference can be found here:
# https://jitsi.github.io/handbook/docs/devops-guide/devops-guide-docker
################################################################################
################################################################################


#
# Basic configuration options
#

# Directory where all configuration will be stored
CONFIG=/federated/apps/jitsi/data/config

EOF
if [ "$JITSI_SCALE" != "server" ]; then
cat >> /federated/apps/jitsi/.env <<EOF
# Exposed HTTP port
HTTP_PORT=9000

# Exposed HTTPS port
HTTPS_PORT=9443

EOF
fi

cat >> /federated/apps/jitsi/.env <<EOF
# System time zone
TZ=UTC

# Public URL for the web service (required)
PUBLIC_URL=https://jitsi.$DOMAIN
EOF

if [ "$JITSI_SCALE" = "server" ]; then
	cat >> /federated/apps/jitsi/.env <<EOF
XMPP_SERVER=xmpp.jitsitest.federatedcomputer.cloud,xmpp.jitsitest2.fedcom.net
EOF
else
	cat >> /federated/apps/jitsi/.env <<EOF
XMPP_SERVER=xmpp.$DOMAIN
EOF
fi

if [ -n "$JITSI_SCALE" ]; then
	# XMPP_AUTH_DOMAIN and XMPP_INTERNAL_MUC_DOMAIN don't
	# need to resolve - they just need to be identical across
	# the involved Jitsi components.
	# So it is safe to use a common (even if nonexistant)
	# domain across all Jitsi Scale clients so the JVB can
	# use the same information for every Prosody instance
	# it connects to.
	cat >> /federated/apps/jitsi/.env <<EOF
XMPP_AUTH_DOMAIN=auth.jitsiscale.federated.computer
XMPP_INTERNAL_MUC_DOMAIN=internal-muc.jitsiscale.federated.computer
EOF
else
	cat >> /federated/apps/jitsi/.env <<EOF
XMPP_AUTH_DOMAIN=auth.$DOMAIN
XMPP_INTERNAL_MUC_DOMAIN=internal-muc.$DOMAIN
EOF
fi

if [ "$JITSI_SCALE" = "server" ]; then
	cat >> /federated/apps/jitsi/.env <<EOF

# XMPP password for JVB client connections
JVB_AUTH_PASSWORD=

# Enable Colibri (statistics/monitoring) so we can check for activity
COLIBRI_REST_ENABLED=1
SHUTDOWN_REST_ENABLED=1
ENABLE_COLIBRI_WEBSOCKET=1
EOF
else

	cat >> /federated/apps/jitsi/.env <<EOF
XMPP_DOMAIN=$DOMAIN
XMPP_BOSH_URL_BASE=http://xmpp.$DOMAIN:5280
XMPP_MUC_DOMAIN=muc.$DOMAIN
XMPP_GUEST_DOMAIN=guest.$DOMAIN
XMPP_RECORDER_DOMAIN=recorder.$DOMAIN

# Media IP addresses to advertise by the JVB
# This setting deprecates DOCKER_HOST_ADDRESS, and supports a comma separated list of IPs
# See the "Running behind NAT or on a LAN environment" section in the Handbook:
# https://jitsi.github.io/handbook/docs/devops-guide/devops-guide-docker#running-behind-nat-or-on-a-lan-environment
#JVB_ADVERTISE_IPS=192.168.1.1,1.2.3.4


#
# JaaS Components (beta)
# https://jaas.8x8.vc
#

# Enable JaaS Components (hosted Jigasi)
#ENABLE_JAAS_COMPONENTS=0

#
# Let's Encrypt configuration
#

# Enable Let's Encrypt certificate generation
#ENABLE_LETSENCRYPT=1

# Domain for which to generate the certificate
#LETSENCRYPT_DOMAIN=meet.example.com

# E-Mail for receiving important account notifications (mandatory)
#LETSENCRYPT_EMAIL=alice@atlanta.net

# Use the staging server (for avoiding rate limits while testing)
#LETSENCRYPT_USE_STAGING=1

#
# Client options
#
ENABLE_SIMULCAST=false
ENABLE_RECORDING=1
ENABLE_LIVESTREAMING=1

#
# Etherpad integration (for document sharing)
#

# Set etherpad-lite URL in docker local network (uncomment to enable)
#ETHERPAD_URL_BASE=http://etherpad.meet.jitsi:9001

# Set etherpad-lite public URL, including /p/ pad path fragment (uncomment to enable)
#ETHERPAD_PUBLIC_URL=https://etherpad.my.domain/p/

# Name your etherpad instance!
ETHERPAD_TITLE="Video Chat"

# The default text of a pad
ETHERPAD_DEFAULT_PAD_TEXT="Welcome to Web Chat!\n\n"

# Name of the skin for etherpad
ETHERPAD_SKIN_NAME=colibris

# Skin variants for etherpad
ETHERPAD_SKIN_VARIANTS="super-light-toolbar super-light-editor light-background full-width-editor"


#
# Basic Jigasi configuration options (needed for SIP gateway support)
#

# SIP URI for incoming / outgoing calls
#JIGASI_SIP_URI=test@sip2sip.info

# Password for the specified SIP account as a clear text
#JIGASI_SIP_PASSWORD=passw0rd

# SIP server (use the SIP account domain if in doubt)
#JIGASI_SIP_SERVER=sip2sip.info

# SIP server port
#JIGASI_SIP_PORT=5060

# SIP server transport
#JIGASI_SIP_TRANSPORT=UDP


#
# Authentication configuration (see handbook for details)
#

# Enable authentication
ENABLE_AUTH=1

# Enable guest access
ENABLE_GUESTS=1

# Select authentication type: internal, jwt, ldap or matrix
AUTH_TYPE=ldap

# JWT authentication
#

# Application identifier
#JWT_APP_ID=my_jitsi_app_id

# Application secret known only to your token generator
#JWT_APP_SECRET=my_jitsi_app_secret

# (Optional) Set asap_accepted_issuers as a comma separated list
#JWT_ACCEPTED_ISSUERS=my_web_client,my_app_client

# (Optional) Set asap_accepted_audiences as a comma separated list
#JWT_ACCEPTED_AUDIENCES=my_server1,my_server2

# LDAP authentication (for more information see the Cyrus SASL saslauthd.conf man page)
#

# LDAP url for connection
LDAP_URL=ldap://ldap.$DOMAIN/

# LDAP base DN. Can be empty
LDAP_BASE=DC=$LDAP_DOMAIN_FIRST,DC=$LDAP_DOMAIN_LAST

# LDAP user DN. Do not specify this parameter for the anonymous bind
LDAP_BINDDN=CN=admin,DC=$LDAP_DOMAIN_FIRST,DC=$LDAP_DOMAIN_LAST

# LDAP user password. Do not specify this parameter for the anonymous bind
LDAP_BINDPW=$LDAP_SECRET

# LDAP filter. Tokens example:

# %1-9 - if the input key is user@mail.domain.com, then %1 is com, %2 is domain and %3 is mail
# %s - %s is replaced by the complete service string
# %r - %r is replaced by the complete realm string
#LDAP_FILTER=(sAMAccountName=%u)
LDAP_FILTER=(mail=%u@$DOMAIN)

# LDAP authentication method
LDAP_AUTH_METHOD=bind

# LDAP version
#LDAP_VERSION=3

# LDAP TLS using
#LDAP_USE_TLS=1

# List of SSL/TLS ciphers to allow
#LDAP_TLS_CIPHERS=SECURE256:SECURE128:!AES-128-CBC:!ARCFOUR-128:!CAMELLIA-128-CBC:!3DES-CBC:!CAMELLIA-128-CBC

# Require and verify server certificate
#LDAP_TLS_CHECK_PEER=1

# Path to CA cert file. Used when server certificate verify is enabled
#LDAP_TLS_CACERT_FILE=/etc/ssl/certs/ca-certificates.crt

# Path to CA certs directory. Used when server certificate verify is enabled
#LDAP_TLS_CACERT_DIR=/etc/ssl/certs

# Wether to use starttls, implies LDAPv3 and requires ldap:// instead of ldaps://
#LDAP_START_TLS=1


#
# Security
#
# Set these to strong passwords to avoid intruders from impersonating a service account
# The service(s) won't start unless these are specified
# Running ./gen-passwords.sh will update .env with strong passwords
# You may skip the Jigasi and Jibri passwords if you are not using those
# DO NOT reuse passwords
#

# XMPP password for Jicofo client connections
JICOFO_AUTH_PASSWORD=

# XMPP password for JVB client connections
JVB_AUTH_PASSWORD=

# XMPP password for Jigasi MUC client connections
JIGASI_XMPP_PASSWORD=

# XMPP recorder password for Jibri client connections
JIBRI_RECORDER_PASSWORD=

# XMPP password for Jibri client connections
JIBRI_XMPP_PASSWORD=
EOF
fi

cat >> /federated/apps/jitsi/.env <<EOF

#
# Docker Compose options
#

# Container restart policy
#RESTART_POLICY=unless-stopped

# Jitsi image version (useful for local development)
JITSI_IMAGE_VERSION=$(current_version jitsi)
EOF

mkdir -p /federated/apps/jitsi/data/config/{web,transcripts,prosody/config,prosody/prosody-plugins-custom,jicofo,jvb,jigasi,jibri}
[ $? -ne 0 ] && fail "Couldn't run mkdir for jitsi configurations"

/federated/apps/jitsi/gen-passwords.sh
[ $? -ne 0 ] && fail "Couldn't run /federated/apps/jitsi/gen-passwords.sh"

echo -ne "done.\n"
}
email_jitsi() {
  echo -ne "* Sending email to customer.."

cat > /federated/apps/mail/data/root/certs/mailfile <<EOF
<html>
<img src="https://www.federated.computer/wp-content/uploads/2023/11/logo.png" alt="" /><br>
<p>
<h4>Jitsi is now installed on $DOMAIN</h4>
<p>
Here is your applications chart with on how to access this service:<br>
<p>
<h4>Applications</h4>
<style type="text/css">
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  overflow:hidden;padding:10px 5px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
.tg .tg-cul6{border-color:inherit;color:#340096;text-align:left;text-decoration:underline;vertical-align:top}
.tg .tg-acii{background-color:#FFF;border-color:inherit;color:#333;text-align:left;vertical-align:top}
.tg .tg-0hty{background-color:#000000;border-color:inherit;color:#ffffff;font-weight:bold;text-align:left;vertical-align:top}
.tg .tg-kwiq{border-color:inherit;color:#000000;text-align:left;vertical-align:top;word-wrap:break-word}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
</style>
<table class="tg" style="undefined;table-layout: fixed; width: 996px">
<colgroup>
<col style="width: 101.333333px">
<col style="width: 203.333333px">
<col style="width: 282.333333px">
<col style="width: 185.33333px">
<col style="width: 78.333333px">
<col style="width: 220.333333px">
</colgroup>
<thead>
  <tr>
    <th class="tg-0hty">Service</th>
    <th class="tg-0hty">Link</th>
    <th class="tg-0hty">User / Pass</th>
    <th class="tg-0hty">Access</th>
    <th class="tg-0hty">Docs</th>
    <th class="tg-0hty">Description</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-kwiq">Jitsi</td>
    <td class="tg-kwiq"><a href="https://jitsi.$DOMAIN" target="_blank" rel="noopener noreferrer"><span style="color:#340096">jitsi.$DOMAIN</span></a></td>
    <td class="tg-kwiq">admin@$DOMAIN<br>admin password in panel</td>
    <td class="tg-kwiq">All users in panel have access using user@$DOMAIN</td>
    <td class="tg-kwiq"><a href="https://documentation.federated.computer/docs/getting_started/welcome/" target="_blank" rel="noopener noreferrer"><span style="color:#340096">Click here</span></a></td>
    <td class="tg-kwiq">Jitsi is a zoom replacement video conferencing solution</td>
  </tr>
</tbody>
</table>
<h4>Thanks for your support!</h4>
<p>
Thank you for your support of Federated Computer. We really appreciate it and hope you have a very successful
time with Federated Core.
<p>
Again, if we can be of any assistance, please don't hesitate to get in touch.
<p>
Support: https://support.federated.computer<br>
Phone: (970) 722-8715<br>
Email: support@federated.computer<br>
<p>
It's <b>your</b> computer. Let's make it work for you!
</html>
EOF

  # Send out e-mail from mail container with details
  docker exec mail bash -c "mail -r admin@$DOMAIN -a \"Content-type: text/html\" -s \"Application installed on $DOMAIN\" $EMAIL < /root/certs/mailfile"
  rm /federated/apps/mail/data/root/certs/mailfile

  kill -9 $SPINPID &> /dev/null
  echo -ne "done.\n"
}
uninstall_jitsi() {
  echo -ne "* Uninstalling jitsi container.."

  # First stop the service
  cd /federated/apps/jitsi && docker compose -f docker-compose.yml -p jitsi down &> /dev/null

  # Delete the app directory
  rm -rf /federated/apps/jitsi

  # Delete the image
  docker image rm jitsi/jvb:$JITSI_IMAGE_VERSION &> /dev/null
  docker image rm jitsi/jicofo:$JITSI_IMAGE_VERSION &> /dev/null
  docker image rm jitsi/prosody:$JITSI_IMAGE_VERSION &> /dev/null
  docker image rm jitsi/web:$JITSI_IMAGE_VERSION &> /dev/null

  # Delete the DNS record
  [[ "${PLUS}" != "true" ]] && docker exec pdns pdnsutil delete-rrset $DOMAIN jitsi A

  # Uninstall the SSO configuration if it exists in authelia (authelia must exist too)
  if [[ $(grep "### Jitsi" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]]; then
    sed -i '/### Jitsi/,/### /{/### PowerDNS/!{/### /!d}}' /federated/apps/authelia/data/config/idproviders.yml
    sed -i '/### Jitsi/d' /federated/apps/authelia/data/config/idproviders.yml
    run_command "/federated/bin/stop authelia"
    run_command "/federated/bin/start authelia"
  fi

  if [[ -d "/federated/apps/jitsiopenid" ]]; then
    cd /federated/apps/jitsiopenid && docker compose -f docker-compose.yml -p jitsiopenid down &> /dev/null
    rm -rf /federated/apps/jitsiopenid
    if [ "$(uname -m)" = "aarch64" ]; then
      docker image rm federatedcomputer/jitsi-go-openid:latest &> /dev/null
    else
      docker image rm mod242/jitsi-go-openid:latest &> /dev/null
    fi
  fi

  echo -ne "done.\n"
}
start_jitsi() {
  # Start service with command to make sure it's up before proceeding
  if [ "$JITSI_SCALE" = "server" ]; then
    start_service "jitsi" "nc -z 192.168.0.28 8080 &> /dev/null" "8"
  else
    start_service "jitsi" "nc -z 192.168.0.25 443 &> /dev/null" "8"
  fi
  # Allow multiple JVBs to connect
  if [ "$JITSI_SCALE" = "client" ]; then
    for i in $(seq 1 10); do
      docker exec -ti jitsi-prosody-1 prosodyctl --config /config/prosody.cfg.lua register jvb$i auth.jitsiscale.federated.computer J17515cAl3-jvb
    done
  fi
  echo -ne "done.\n"
}
configsso_jitsi() {
  if [[ "${PLUS}" != "true" ]]; then
  echo -ne "* Configuring jitsi container with SSO.."

  [ ! -d "/federated/apps/authelia" ] && failcheck "Authelia is not installed. You need this first before continuing."
  [ ! -f "/federated/apps/authelia/data/config/idproviders.yml" ] && failcheck "Authelia idproviders.yml is missing."
  [[ $(grep "### Jitsi" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]] && failcheck "Authelia already has a Jitsi configuration."

  JITSI_JWT_APP_SECRET=$(create_password);
  JITSI_CLIENT_SECRET=$(create_password);
  #echo "$JITSI_CLIENT_SECRET" > /federated/apps/jitsi/.jitsiclient.secret
  #chmod 600 /federated/apps/jitsi/.jitsiclient.secret
  JITSI_CLIENT_SECRET_HASH=$(docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --password $JITSI_CLIENT_SECRET | awk '{ print $2 }')

cat >> /federated/apps/authelia/data/config/idproviders.yml <<EOF
      ### Jitsi
      - client_id: 'jitsi'
        client_name: 'Jitsi'
        client_secret: $JITSI_CLIENT_SECRET_HASH
        consent_mode: 'implicit'
        public: false
        authorization_policy: 'one_factor'
        redirect_uris:
          - 'https://jitsi.$DOMAIN/jitsi-openid/callback'
        scopes:
          - 'openid'
          - 'profile'
          - 'email'
        userinfo_signed_response_alg: 'none'
        token_endpoint_auth_method: 'client_secret_basic'
EOF

  # Restart Authelia for changes to take the above configuration
  run_command "/federated/bin/stop authelia"
  run_command "/federated/bin/start authelia"

  sed -i "s/AUTH_TYPE=.*/AUTH_TYPE=jwt/g" /federated/apps/jitsi/.env
  sed -i "s/#JWT_APP_ID=.*/JWT_APP_ID=jitsi.$DOMAIN/g" /federated/apps/jitsi/.env
  sed -i "s/#JWT_APP_SECRET=.*/JWT_APP_SECRET=$JITSI_JWT_APP_SECRET/g" /federated/apps/jitsi/.env
  sed -i "s/#JWT_ACCEPTED_ISSUERS=.*/JWT_ACCEPTED_ISSUERS=jitsi/g" /federated/apps/jitsi/.env
  sed -i "s/#JWT_ACCEPTED_AUDIENCES=.*/JWT_ACCEPTED_AUDIENCES=jitsi/g" /federated/apps/jitsi/.env
  echo "TOKEN_AUTH_URL=https://jitsi.$DOMAIN/jitsi-openid/authenticate?state={state}&room={room}" >> /federated/apps/jitsi/.env

  # Install Jitsi OpenID GO plugin
  mkdir -p /federated/apps/jitsiopenid &> /dev/null

  if [ "$(uname -m)" = "aarch64" ]; then
    CONTAINER="federatedcomputer/jitsi-go-openid"
  else
    CONTAINER="mod242"
  fi

cat >> /federated/apps/jitsiopenid/docker-compose.yml <<EOF
services:
  jitsiopenid:
    image: ${CONTAINER}/jitsi-go-openid:\${IMAGE_VERSION}
    container_name: jitsiopenid
    hostname: jitsiopenid.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.46
    extra_hosts:
      - "authelia.$DOMAIN:$EXTERNALIP"
    env_file:
      - ./.env
    labels:
      - "traefik.enable=true"
      - "traefik.http.services.srv-jitsiopenid.loadbalancer.server.port=3001"
      - "traefik.http.middlewares.strip-jitsiopenid.stripprefix.prefixes=/jitsi-openid"
      - "traefik.http.routers.jitsiopenid.middlewares=strip-jitsiopenid"
      - "traefik.http.routers.jitsiopenid.service=srv-jitsiopenid"
      - "traefik.http.routers.jitsiopenid.entrypoints=websecure"
      - "traefik.http.routers.jitsiopenid.rule=Host(\`jitsi.$DOMAIN\`) && PathPrefix(\`/jitsi-openid\`)"
      - "traefik.http.routers.jitsiopenid.tls=true"
      - "traefik.http.routers.jitsiopenid.tls.certresolver=letsencrypt"

networks:
  core:
    external: true
EOF

[[ "${PLUS}" = "true" ]] && sed -i "s/letsencrypt/httpresolver/g" /federated/apps/jitsiopenid/docker-compose.yml

cat > /federated/apps/jitsiopenid/.env <<EOF
IMAGE_VERSION="latest"
JITSI_SECRET=$JITSI_JWT_APP_SECRET
JITSI_URL=https://jitsi.$DOMAIN
JITSI_SUB=jitsi.$DOMAIN
ISSUER_BASE_URL=https://authelia.$DOMAIN
BASE_URL=https://jitsi.$DOMAIN/jitsi-openid
CLIENT_ID=jitsi
SECRET=$JITSI_CLIENT_SECRET
PREJOIN=false
DEEPLINK=true
NAME_KEY=name
EOF
chmod 600 /federated/apps/jitsiopenid/.env

  run_command "/federated/bin/stop jitsi"
  run_command "/federated/bin/start jitsi"
  run_command "/federated/bin/start jitsiopenid"

  echo -ne "done.\n"
  fi
}
configsso_jitsi_plus() {
  JITSI_CLIENT_SECRET=$(cat /federated/apps/jitsi/.jitsi.client.secret)
  JITSI_JWT_APP_SECRET=$(cat /federated/apps/jitsi/.jitsi.jwt.app.secret)

  sed -i "s/AUTH_TYPE=.*/AUTH_TYPE=jwt/g" /federated/apps/jitsi/.env
  sed -i "s/#JWT_APP_ID=.*/JWT_APP_ID=jitsi.$DOMAIN/g" /federated/apps/jitsi/.env
  sed -i "s/#JWT_APP_SECRET=.*/JWT_APP_SECRET=$JITSI_JWT_APP_SECRET/g" /federated/apps/jitsi/.env
  sed -i "s/#JWT_ACCEPTED_ISSUERS=.*/JWT_ACCEPTED_ISSUERS=jitsi/g" /federated/apps/jitsi/.env
  sed -i "s/#JWT_ACCEPTED_AUDIENCES=.*/JWT_ACCEPTED_AUDIENCES=jitsi/g" /federated/apps/jitsi/.env
  echo "TOKEN_AUTH_URL=https://jitsi.$DOMAIN/jitsi-openid/authenticate?state={state}&room={room}" >> /federated/apps/jitsi/.env

  # Install Jitsi OpenID GO plugin
  mkdir -p /federated/apps/jitsiopenid &> /dev/null

  if [ "$(uname -m)" = "aarch64" ]; then
    CONTAINER="federatedcomputer/jitsi-go-openid"
  else
    CONTAINER="mod242"
  fi

cat >> /federated/apps/jitsiopenid/docker-compose.yml <<EOF
services:
  jitsiopenid:
    image: ${CONTAINER}/jitsi-go-openid:\${IMAGE_VERSION}
    container_name: jitsiopenid
    hostname: jitsiopenid.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.46
    extra_hosts:
      - "authelia.$DOMAIN:$EXTERNALIP"
    env_file:
      - ./.env
    labels:
      - "traefik.enable=true"
      - "traefik.http.services.srv-jitsiopenid.loadbalancer.server.port=3001"
      - "traefik.http.middlewares.strip-jitsiopenid.stripprefix.prefixes=/jitsi-openid"
      - "traefik.http.routers.jitsiopenid.middlewares=strip-jitsiopenid"
      - "traefik.http.routers.jitsiopenid.service=srv-jitsiopenid"
      - "traefik.http.routers.jitsiopenid.entrypoints=websecure"
      - "traefik.http.routers.jitsiopenid.rule=Host(\`jitsi.$DOMAIN\`) && PathPrefix(\`/jitsi-openid\`)"
      - "traefik.http.routers.jitsiopenid.tls=true"
      - "traefik.http.routers.jitsiopenid.tls.certresolver=letsencrypt"

networks:
  core:
    external: true
EOF

sed -i "s/letsencrypt/httpresolver/g" /federated/apps/jitsiopenid/docker-compose.yml

cat > /federated/apps/jitsiopenid/.env <<EOF
IMAGE_VERSION="latest"
JITSI_SECRET=$JITSI_JWT_APP_SECRET
JITSI_URL=https://jitsi.$DOMAIN
JITSI_SUB=jitsi.$DOMAIN
ISSUER_BASE_URL=https://authelia.$DOMAIN
BASE_URL=https://jitsi.$DOMAIN/jitsi-openid
CLIENT_ID=jitsi
SECRET=$JITSI_CLIENT_SECRET
PREJOIN=false
DEEPLINK=true
NAME_KEY=name
EOF
chmod 600 /federated/apps/jitsiopenid/.env

  run_command "/federated/bin/stop jitsi"
  run_command "/federated/bin/start jitsi"
  run_command "/federated/bin/start jitsiopenid"
}