#!/bin/bash

help() {
  echo "Usage: $1 <options>"
  echo "       -c : Clean capif services"
  echo "       -v : Clean vault service"
  echo "       -r : Clean register service"
  echo "       -m : Clean monitoring service"
  echo "       -a : Clean all services"
  echo "       -h : show this help"
  exit 1
}

if [[ $# -lt 1 ]]
then
  echo "You must specify an option before run script."
  help
fi

FILES=()
echo "${FILES[@]}"

# Read params
while getopts "cvrahm" opt; do
  case $opt in
    c)
      echo "Remove Capif services"
      FILES+=("docker-compose-capif.yml")
      ;;
    v)
      echo "Remove vault service"
      FILES+=("docker-compose-vault.yml")
      ;;
    r)
      echo "Remove register service"
      FILES+=("docker-compose-register.yml")
      ;;
    m)
      echo "Remove monitoring service"
      FILES+=("../monitoring/docker-compose.yml")
      ;;
    a)
      echo "Remove all services"
      FILES=("docker-compose-capif.yml" "docker-compose-vault.yml" "docker-compose-register.yml" "../monitoring/docker-compose.yml")
      ;;
    h)
      help
      ;;
    \?)
      echo "Not valid option: -$OPTARG" >&2
      help
      exit 1
      ;;
    :)
      echo "The -$OPTARG option requires an argument." >&2
      help
      exit 1
      ;;
  esac
done
echo "after check"
echo "${FILES[@]}"

for FILE in "${FILES[@]}"; do
  echo "Executing 'docker-compose down' for file $FILE"
  docker-compose -f "$FILE" down --rmi all
  status=$?
    if [ $status -eq 0 ]; then
        echo "*** Removed Service from $FILE ***"
    else
        echo "*** Some services of $FILE failed on clean ***"
    fi
done

docker network rm capif-network

echo "Clean complete."
