#!/usr/bin/env bash

# import env variables from .env
set -a
source .env

DB_PASSWORD=$(echo "$DATABASE_URL" | awk -F':' '{print $3}' | awk -F'@' '{print $1}')
DB_PORT=$(echo "$DATABASE_URL" | awk -F':' '{print $4}' | awk -F'/' '{print $1}')
DB_NAME=$(echo "$DATABASE_URL" | awk -F'/' '{print $4}')
DB_CONTAINER_NAME="$DB_NAME-postgres"

REDIS_PORT=${REDIS_PORT:-6379}
REDIS_CONTAINER_NAME="$DB_NAME-redis"

if ! [ -x "$(command -v docker)" ] && ! [ -x "$(command -v podman)" ]; then
  echo -e "Docker or Podman is not installed. Please install docker or podman and try again.\nDocker install guide: https://docs.docker.com/engine/install/\nPodman install guide: https://podman.io/getting-started/installation"
  exit 1
fi

# determine which docker command to use
if [ -x "$(command -v docker)" ]; then
  DOCKER_CMD="docker"
elif [ -x "$(command -v podman)" ]; then
  DOCKER_CMD="podman"
fi

if ! $DOCKER_CMD info > /dev/null 2>&1; then
  echo "$DOCKER_CMD daemon is not running. Please start $DOCKER_CMD and try again."
  exit 1
fi

# # Check if ports are in use
# if command -v nc >/dev/null 2>&1; then
#   if nc -z localhost "$DB_PORT" 2>/dev/null; then
#     echo "Port $DB_PORT is already in use."
#     exit 1
#   fi
#   if nc -z localhost "$REDIS_PORT" 2>/dev/null; then
#     echo "Port $REDIS_PORT is already in use."
#     exit 1
#   fi
# else
#   echo "Warning: Unable to check if ports are in use (netcat not installed)"
#   read -p "Do you want to continue anyway? [y/N]: " -r REPLY
#   if ! [[ $REPLY =~ ^[Yy]$ ]]; then
#     echo "Aborting."
#     exit 1
#   fi
# fi

# Start PostgreSQL if not running
if [ "$($DOCKER_CMD ps -q -f name=$DB_CONTAINER_NAME)" ]; then
  echo "Database container '$DB_CONTAINER_NAME' already running"
else
  if [ "$($DOCKER_CMD ps -q -a -f name=$DB_CONTAINER_NAME)" ]; then
    $DOCKER_CMD start "$DB_CONTAINER_NAME"
    echo "Existing database container '$DB_CONTAINER_NAME' started"
  else
    $DOCKER_CMD run -d \
      --name $DB_CONTAINER_NAME \
      -e POSTGRES_USER="postgres" \
      -e POSTGRES_PASSWORD="$DB_PASSWORD" \
      -e POSTGRES_DB="$DB_NAME" \
      -p "$DB_PORT":5432 \
      docker.io/postgres && echo "Database container '$DB_CONTAINER_NAME' was successfully created"
  fi
fi

# Start Redis if not running
if [ "$($DOCKER_CMD ps -q -f name=$REDIS_CONTAINER_NAME)" ]; then
  echo "Redis container '$REDIS_CONTAINER_NAME' already running"
else
  if [ "$($DOCKER_CMD ps -q -a -f name=$REDIS_CONTAINER_NAME)" ]; then
    $DOCKER_CMD start "$REDIS_CONTAINER_NAME"
    echo "Existing Redis container '$REDIS_CONTAINER_NAME' started"
  else
    $DOCKER_CMD run -d \
      --name $REDIS_CONTAINER_NAME \
      -p "$REDIS_PORT":6379 \
      docker.io/redis && echo "Redis container '$REDIS_CONTAINER_NAME' was successfully created"
  fi
fi
