#!/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.."

  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
  get_externalip

cat > /federated/apps/collabora/docker-compose.yml <<EOF
services:
  collabora:
    image: collabora/code:\${IMAGE_VERSION}
    container_name: collabora
    hostname: collabora.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.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:
  core:
    external: true
EOF

cat > /federated/apps/collabora/.env <<EOF
IMAGE_VERSION=$(current_version collabora)
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"

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

  echo -ne "done."
}
uninstall_collabora() {
  echo -ne "* Uninstalling collabora container.."

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

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

  # Delete the image
  docker image rm collabora:$IMAGE_VERSION &> /dev/null

  # Delete the DNS record
  docker exec pdns pdnsutil delete-rrset $DOMAIN collabora A

  echo -ne "done.\n"
}
