#!/bin/bash
#
# Cal.com Service

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

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

  if [ ! -d "/federated/apps/calcom" ]; then
    mkdir -p /federated/apps/calcom
  fi

  DOMAIN_ARRAY=(${DOMAIN//./ })
  DOMAIN_FIRST=${DOMAIN_ARRAY[0]}
  DOMAIN_LAST=${DOMAIN_ARRAY[1]}

cat > /federated/apps/calcom/docker-compose.yml <<EOF
version: '3.7'
services:
  calcom:
    image: federatedcomputer/calcom:\${IMAGE_VERSION}
    container_name: calcom
    hostname: calcom.$DOMAIN
    domainname: $DOMAIN
    restart: always
    networks:
      federated:
        ipv4_address: 172.99.0.29
#    build:
#      context: .
#      dockerfile: Dockerfile
#      args:
#        NEXT_PUBLIC_WEBAPP_URL: \${NEXT_PUBLIC_WEBAPP_URL}
#        NEXT_PUBLIC_LICENSE_CONSENT: \${NEXT_PUBLIC_LICENSE_CONSENT}
#        CALCOM_TELEMETRY_DISABLED: \${CALCOM_TELEMETRY_DISABLED}
#        NEXTAUTH_SECRET: \${NEXTAUTH_SECRET}
#        CALENDSO_ENCRYPTION_KEY: \${CALENDSO_ENCRYPTION_KEY}
#        DATABASE_URL: \${DATABASE_URL}
    env_file: ./.env

networks:
  federated:
    external: true
EOF

cp /federated/lib/files/calcom/.env /federated/apps/calcom/

# Fix up .env file for our DOMAIN
sed -i "s#NEXT_PUBLIC_WEBAPP_URL=.*#NEXT_PUBLIC_WEBAPP_URL=http://calcom.$DOMAIN:3000#g" /federated/apps/calcom/.env

NEXTAUTH_SECRET=`openssl rand -base64 32`
sed -i "s#NEXTAUTH_SECRET=.*#NEXTAUTH_SECRET=$NEXTAUTH_SECRET#g" /federated/apps/calcom/.env

CALENDSO_ENCRYPTION_KEY=`dd if=/dev/urandom bs=1K count=1 2>/dev/null | md5sum | awk '{ print $1 }'`
sed -i "s#CALENDSO_ENCRYPTION_KEY=.*#CALENDSO_ENCRYPTION_KEY=$CALENDSO_ENCRYPTION_KEY#g" /federated/apps/calcom/.env

sed -i "s#POSTGRES_USER=.*#POSTGRES_USER=calcom#g" /federated/apps/calcom/.env
sed -i "s#POSTGRES_PASSWORD=.*#POSTGRES_PASSWORD=$CALCOM_SECRET#g" /federated/apps/calcom/.env
sed -i "s#POSTGRES_DB=.*#POSTGRES_DB=calcom#g" /federated/apps/calcom/.env
sed -i "s#DATABASE_HOST=.*#DATABASE_HOST=postgresql\.$DOMAIN:5432#g" /federated/apps/calcom/.env
sed -i "s#DATABASE_URL=.*#DATABASE_URL=postgresql://calcom:$CALCOM_SECRET@postgresql\.$DOMAIN/calcom#g" /federated/apps/calcom/.env

cat >> /federated/apps/calcom/.env <<EOF
IMAGE_VERSION="1.0"
VIRTUAL_PROTO=http
VIRTUAL_PORT=3000
VIRTUAL_HOST=calcom.$DOMAIN
EOF
chmod 600 /federated/apps/calcom/.env
 
kill -9 $SPINPID &> /dev/null
echo -ne "done."
}

start_calcom() {
  # Start service with command to make sure it's up before proceeding
  start_service "calcom" "nc -z 172.99.0.29 3000 &> /dev/null"

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