#!/usr/bin/env bash

function showHelp() {
  echo "-------------------------------------------------------------------"
  echo "Run Script for Docker container Database service and GUI Admin tool"
  echo "-------------------------------------------------------------------"
  echo ""
  printf "Usage: ./db.sh [flags]\n\n"

  echo "--------|-------------------------------------------------"
  echo "Flags   | Description"
  echo "--------|-------------------------------------------------"
  echo "blank   | Starts database only"
  echo "all     | Starts database and Admin GUI"
  echo "down    | Stop all containers and cleanup"
  echo "start   | Start all containers"
  echo "stop    | Stop all containers"
  echo "restart | Restart all containers"
  echo "reboot  | Restart all containers"
  echo "--------|-------------------------------------------------"
}

function allServicesUp() {
  docker compose up -d
  echo -e "DB connection on $(docker network inspect bridge|grep Gateway|awk '{$1=$1};1') Port 5432"
  echo -e "pgAdmin4 GUI:    http://localhost:5050"
  echo -e "MySQL Workbench: http://localhost:3100"
}

function databaseUp() {
  docker compose up -d database
  echo -e "DB connection on $(docker network inspect bridge|grep Gateway|awk '{$1=$1};1') Port 5432"
}

function databaseDown() {
  docker compose down
}

function databaseStart() {
  docker compose start
}

function databaseStop() {
  docker compose stop
}

function databaseRestart() {
  docker compose restart
}

if [ "$1" == "all" ]; then
  # Stop and remove containers, networks
  allServicesUp
elif [ "$1" == "down" ]; then
  # Stop and remove containers, networks
  databaseDown
elif [ "$1" == "start" ]; then
  # Stop containers
  databaseStart
elif [ "$1" == "stop" ]; then
  # Stop containers
  databaseStop
elif [ "$1" == "restart" ] || [ "$1" == "reboot" ]; then
  databaseRestart
elif [ "$1" == "--help" ] || [ "$1" == "-h" ] || [ "$1" == "?" ]; then
  # Show usage help
  showHelp
else
  databaseUp
fi
