#!/bin/bash
#
# Jitsiopenid Service
# This logic is in jitsi.sh (and used there) instead of here, but keeping this around anyway

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

config_jitsiopenid() {
  echo -ne "\n* Configuring /federated/apps/jitsiopenid container.."

  if [ ! -d "/federated/apps/jitsiopenid" ]; then
    mkdir -p /federated/apps/jitsiopenid &> /dev/null
  fi

cat > /federated/apps/jitsiopenid/docker-compose.yml <<EOF
services:
  jitsiopenid:
    image: mod242/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\`) || Host(\`jitsi.$DOMAIN\`) && PathPrefix(\`/callback\`)"
      - "traefik.http.routers.jitsiopenid.tls=true"
      - "traefik.http.routers.jitsiopenid.tls.certresolver=letsencrypt"

networks:
  core:
    external: true
EOF

JWT_APP_SECRET=$(grep JWT_APP_SECRET /federated/apps/jitsi/.env | awk -F= '{ print $2 }')
JITSI_CLIENT_SECRET=$(cat /federated/apps/jitsi/.jisticlient.secret)

cat > /federated/apps/jitsiopenid/.env <<EOF
IMAGE_VERSION="latest"
JITSI_SECRET=$JITSI_SECRET
JITSI_URL=https://jitsi.$DOMAIN
JITSI_SUB=jitsi.$DOMAIN
ISSUER_BASE_URL=https://authelia.$DOMAIN
BASE_URL=https://jitsi.$DOMAIN
CLIENT_ID=jitsi
SECRET=$JITSI_CLIENT_SECRET
PREJOIN=false
DEEPLINK=true
NAME_KEY=name
EOF
chmod 600 /federated/apps/jitsiopenid/.env
 
echo -ne "done."
}
start_jitsiopenid() {
  # Start service with command to make sure it's up before proceeding
  start_service "jitsiopenid" "nc -z 192.168.0.46 3001 &> /dev/null" "7"

  echo -ne "done."
}
