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

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" ] && echo "* $i not installed, skipping." && 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" ] && echo "* $i not installed, skipping." && continue

    # If app is already stopped then skip
    [ ! "$(docker ps -f "name=$i" -f "status=running" -q)" ] && echo "* $i is already stopped." && continue

    # If app is jitsi then check status of jitsi_web_1 since jitsi is named different
    [ "$i" = "jitsi" ] && [ ! "$(docker ps -f "name=jitsi_web_1" -f "status=running" -q)" ] && echo "* $i is already stopped." && continue

    # 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
  [ ! "$(docker ps -f "name=$SERVICE" -f "status=running" -q)" ] && echo "* $SERVICE is already stopped." && exit 2

  # If app is jitsi then check status of jitsi_web_1 since jitsi is named different
  [ "$SERVICE" = "jitsi" ] && [ ! "$(docker ps -f "name=jitsi_web_1" -f "status=running" -q)" ] && echo "* $SERVICE is already stopped." && exit 2

  # Stop service
  stopservice "$SERVICE"
else
  usage
fi
