#!/bin/bash
#
# Connector Service

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

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

  if [ ! -d "/federated/apps/connector" ]; then
    mkdir -p /federated/apps/connector/data/source/public/downloads
  fi

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

cat > /federated/apps/connector/docker-compose.yml <<EOF
services:
  connector:
    image: federatedcomputer/web-connector:\${IMAGE_VERSION}
    container_name: connector
    hostname: connector.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.27
    ports:
      - 3000:3000
    env_file:
      - ./.env
    volumes:
      - ./data/source/public/downloads:/source/public/downloads

networks:
  core:
    external: true
EOF

COOKIE_SECRET=`dd if=/dev/urandom bs=1K count=1 2>/dev/null | md5sum | awk '{ print $1 }'`

cat > /federated/apps/connector/.env <<EOF
DOMAIN=$DOMAIN
IMAGE_VERSION="latest"
LDAP_URL=ldap://ldap.$DOMAIN
LDAP_BASE_DN=dc=$DOMAIN_FIRST,dc=$DOMAIN_LAST
LDAP_ADMIN_USERNAME=admin
LDAP_ADMIN_PASSWORD=$LDAP_SECRET
COOKIE_SECRET=$COOKIE_SECRET
VIRTUAL_PROTO=http
VIRTUAL_PORT=3000
VIRTUAL_HOST=connector.$DOMAIN
EOF
chmod 600 /federated/apps/connector/.env

cp /federated/lib/files/connector/FederatedCore.dmg /federated/apps/connector/data/source/public/downloads/
 
kill -9 $SPINPID &> /dev/null
echo -ne "done."
}

start_connector() {
  # Start /federated/apps/connector with output to /dev/null
  echo -ne "\n* Starting /federated/apps/connector service.."
  spin &
  SPINPID=$!

  if [ $DEBUG ]; then
    # Start /federated/apps/connector with output to console for debug
    docker compose -f /federated/apps/connector/docker-compose.yml -p connector up
    [ $? -eq 0 ] && echo -ne "done.\n" || fail "There was a problem starting service /federated/apps/connector"
  else
    docker compose -f /federated/apps/connector/docker-compose.yml -p connector up -d &> /dev/null

    # Keep trying connector port 80 to make sure it's up
    # before we proceed
    RETRY="30"
    while [ $RETRY -gt 0 ]; do
      nc -z 192.168.0.27 3000 &> /dev/null
      if [ $? -eq 0 ]; then
        break
      else
        if [ "$RETRY" == 1 ]; then
          docker compose -f /federated/apps/connector/docker-compose.yml -p connector down &> /dev/null
          kill -9 $SPINPID &> /dev/null
          fail "There was a problem starting service /federated/apps/connector\nCheck the output of 'docker logs connector' or turn on\ndebug with -d"
        fi
        ((RETRY--))
        sleep 7
      fi
    done
  fi

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