#!/bin/bash

HOSTNAME=capifcore
MONITORING_STATE=false
DEPLOY=all
DEPLOY_BACKOFFICE=${DEPLOY_BACKOFFICE:-false}

# Get docker compose version
docker_version=$(docker compose version --short | cut -d',' -f1)
IFS='.' read -ra version_components <<< "$docker_version"

if [ "${version_components[0]}" -ge 2 ] && [ "${version_components[1]}" -ge 10 ]; then
  echo "Docker compose version it greater than 2.10"
else
  echo "Docker compose version is not valid. Should be greater than 2.10"
  exit 1
fi

# Read params
while getopts ":h:m:" opt; do
  case $opt in
    h)
      HOSTNAME="$OPTARG"
      ;;
    m)
      MONITORING_STATE="$OPTARG"
      ;;    
    \?)
      echo "Opción no válida: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "La opción -$OPTARG requiere un argumento." >&2
      exit 1
      ;;
  esac
done

if [ "$MONITORING_STATE" = true ] ; then
    docker compose -f "./docker-compose-monitoring.yml" down 
    status=$?
    if [ $status -eq 0 ]; then
        echo "*** Monitoring Stack Stopped ***"
    else
        echo "*** Monitoring Stack failed to stopt ***"
        exit $status
    fi
fi

docker compose -f "./docker-compose-vault.yml"  down

status=$?
if [ $status -eq 0 ]; then
    echo "*** Vault Service Stopped ***"
else
    echo "*** Vault failed to stop ***"
    exit $status
fi



CAPIF_HOSTNAME=$HOSTNAME MONITORING=$MONITORING_STATE docker compose -f "./docker-compose-capif.yml" down

status=$?
if [ $status -eq 0 ]; then
    echo "*** All Capif services are stopped ***"
else
    echo "*** Some Capif services failed to stop ***"
    exit $status
fi


CAPIF_PRIV_KEY_BASE_64=$(echo "$(cat nginx/certs/server.key)")
CAPIF_PRIV_KEY=$CAPIF_PRIV_KEY_BASE_64 docker compose -f "./docker-compose-register.yml" down

status=$?
if [ $status -eq 0 ]; then
    echo "*** Register Service are stopped ***"
else
    echo "*** Register Service failed to stop ***"
fi


if [ $DEPLOY_BACKOFFICE = "false" ]; then
    exit $status
fi


docker compose -f "./docker-compose-backoffice.yml"  down

status=$?
if [ $status -eq 0 ]; then
    echo "*** Backoffice Service are stopped ***"
else
    echo "*** Backoffice Service failed to stop ***"
fi

exit $status
