#!/bin/bash
#
# Federated Stop Script
. /federated/lib/functions.sh
. /etc/federated

usage() {
  printf -v SERVICES_JOINED '%s|' "${SERVICES[@]}"
  echo "$0: ${SERVICES_JOINED%|}"
  exit 2
}
stopservice() {
  echo -ne "* Stopping $1.."
  spin &
  SPINPID=$!

  cd /federated/apps/$1 && docker compose -f docker-compose.yml -p $1 down &> /dev/null
  [ $? -ne 0 ] && echo -ne "\nThere was a problem stopping service /federated/apps/$1\nCheck the output of 'docker logs $1' while stopping or run\ndocker compose -f /federated/apps/$1/docker-compose.yml -p $1 down\n\n"

  disown $SPINPID &> /dev/null
  kill -9 $SPINPID &> /dev/null
  echo "done."
}
stopservice_all_old() {
  for i in "${SERVICES[@]}"; do
    # If app isn't installed then skip
    [ ! -d "/federated/apps/$i" ] && continue

    echo "* Stopping $i.."
    cd /federated/apps/$i && docker compose -f docker-compose.yml -p $i down
  done
}
stopservice_all() {
  echo "* Stopping $i."
  cd /federated/apps/$1 && docker compose -f docker-compose.yml -p $1 down &> /dev/null
  [ $? -ne 0 ] && echo -ne "\nThere was a problem stopping service /federated/apps/$1\nCheck the output of 'docker logs $1' while stopping or run\ndocker compose -f /federated/apps/$1/docker-compose.yml -p $1 down\n\n"
}

[[ $# -ne 1 ]] && usage
SERVICE=$1

if [ "$SERVICE" = "all" ]; then
  for i in "${SERVICES[@]}"; do
    # If app isn't installed then skip
    [ ! -d "/federated/apps/$i" ] && continue

    # If app is already stopped then skip
    # If app is jitsi then check status of jitsi-web-1 or jitsi-jvb-1
    if [ "$i" = "jitsi" ]; then
      if [ "$JITSI_SCALE" = "server" ]; then
        [ ! "$(docker ps -f "name=jitsi-jvb-1" -f "status=running" -q)" ] && echo "* $i is already stopped." && continue
      else
        [ ! "$(docker ps -f "name=jitsi-web-1" -f "status=running" -q)" ] && echo "* $i is already stopped." && continue
      fi
    else
      [ ! "$(docker ps -f "name=$i" -f "status=running" -q)" ] && echo "* $i is already stopped." && continue
    fi

    # Run thread in stopservice_all function
    stopservice_all "$i" &
  done

  wait
  exit 0
fi

if printf '%s\0' "${SERVICES[@]}" | grep -Fxqz -- "$SERVICE"; then
  # If app is already stopped then skip
  # If app is jitsi then check status of jitsi-web-1 or jitsi-jvb-1
  if [ "$SERVICE" = "jitsi" ]; then
    if [ "$JITSI_SCALE" = "server" ]; then
      [ ! "$(docker ps -f "name=jitsi-jvb-1" -f "status=running" -q)" ] && echo "* $SERVICE is already stopped." && exit 2
    else
      [ ! "$(docker ps -f "name=jitsi-web-1" -f "status=running" -q)" ] && echo "* $SERVICE is already stopped." && exit 2
    fi
  else
    [ ! "$(docker ps -f "name=$SERVICE" -f "status=running" -q)" ] && echo "* $SERVICE is already stopped." && exit 2
  fi

  # Stop service
  stopservice "$SERVICE"
else
  usage
fi
