#!/bin/bash

HOSTNAME=capifcore
MONITORING_STATE=false
DEPLOY=all

#Needed to avoid write permissions on bind volumes with prometheus and grafana
DUID=$(id -u)
DGID=$(id -g)

# 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

echo Nginx hostname will be $HOSTNAME, deploy $DEPLOY, monitoring $MONITORING_STATE

if [ "$MONITORING_STATE" == "true" ] ; then
    echo '***Monitoring set as true***'
    echo '***Creating Monitoging stack***'

    DUID=$DUID DGID=$DGID docker compose -f "./docker-compose-monitoring.yml" up --detach
    status=$?
    if [ $status -eq 0 ]; then
        echo "*** Monitoring Stack Runing ***"
    else
        echo "*** Monitoring Stack failed to start ***"
        exit $status
    fi
fi

docker network create capif-network

docker compose -f "./docker-compose-vault.yml"  up --detach --build

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

CAPIF_HOSTNAME=$HOSTNAME MONITORING=$MONITORING_STATE docker compose -f "./docker-compose-capif.yml" up --detach --build

status=$?
if [ $status -eq 0 ]; then
    echo "*** All Capif services are running ***"
else
    echo "*** Some Capif services failed to start ***"
    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"  up --detach --build

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

exit $status
