#!/bin/bash
#
# Collabora Service

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

config_collabora() {
  echo -ne "\n* Configuring /federated/apps/collabora container.."
  spin &
  SPINPID=$!

  if [ ! -d "/federated/apps/collabora" ]; then
    mkdir -p /federated/apps/collabora/data/root/certs &> /dev/null
    mkdir -p /federated/apps/collabora/data/opt/collaboraoffice/share/fonts/truetype &> /dev/null
    cp /federated/certs/certs/$DOMAIN.crt /federated/certs/private/$DOMAIN.key /federated/apps/collabora/data/root/certs/
    chown 104 /federated/apps/collabora/data/root/certs/*
  fi

cat > /federated/apps/collabora/docker-compose.yml <<EOF
version: '3.7'

services:
  collabora:
    image: collabora/code:\${IMAGE_VERSION}
    container_name: collabora
    hostname: collabora.$DOMAIN
    domainname: $DOMAIN
    restart: always
    networks:
      federated:
        ipv4_address: 172.99.0.17
    extra_hosts:
      - "nextcloud.$DOMAIN:$EXTERNALIP"
    ports:
      - "9980:9980"
    volumes:
      - ./data/root:/root
      - ./data/opt/collaboraoffice/share/fonts/truetype:/opt/collaboraoffice/share/fonts/truetype
#      - ./data/root/certs/$DOMAIN.crt:/etc/coolwsd/cert.pem
#      - ./data/root/certs/$DOMAIN.key:/etc/coolwsd/key.pem
    env_file:
      - ./.env
    cap_add:
      - MKNOD
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.collabora.rule=Host(\`collabora.$DOMAIN\`)"
      - "traefik.http.routers.collabora.entrypoints=websecure"
      - "traefik.http.routers.collabora.tls.certresolver=letsencrypt"
      - "traefik.http.services.collabora.loadbalancer.server.port=9980"

networks:
  federated:
    external: true
EOF

cat > /federated/apps/collabora/.env <<EOF
IMAGE_VERSION=23.05.10.1.1
domain=nextcloud.$DOMAIN
server_name=collabora.$DOMAIN
extra_params=--o:ssl.enable=false --o:ssl.termination=true
EOF
chmod 600 /federated/apps/collabora/.env

# Extract extra fonts into collabora
tar zxvf /federated/lib/files/collabora/fonts.tar.gz -C /federated/apps/collabora/data/opt/collaboraoffice/share/fonts/truetype/
[ $? -ne 0 ] && fail "Couldn't extract files/collabora/fonts.tar.gz into collabora"

kill -9 $SPINPID &> /dev/null
echo -ne "done."
}
start_collabora() {
  # Start service with command to make sure it's up before proceeding
  start_service "collabora" "nc -z 172.99.0.17 9980 &> /dev/null" "15"

  kill -9 $SPINPID &> /dev/null
  echo -ne "done."
}
