#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
STACK_ENV="${STACK_ENV:-$ROOT_DIR/stack.env}"

if [[ -f "$STACK_ENV" ]]; then
  set -a
  . "$STACK_ENV"
  set +a
fi

STACK_ID="${GIA_STACK_ID:-${STACK_ID:-}}"
STACK_ID="$(echo "$STACK_ID" | tr -cs 'a-zA-Z0-9._-' '-' | sed 's/^-*//; s/-*$//')"

name_with_stack() {
  local base="$1"
  if [[ -n "$STACK_ID" ]]; then
    echo "${base}_${STACK_ID}"
  else
    echo "$base"
  fi
}

MANTICORE_CONTAINER="$(name_with_stack "manticore_gia")"
MANTICORE_CONFIG_FILE="${MANTICORE_CONFIG_FILE:-$ROOT_DIR/utilities/memory/manticore.conf}"
MANTICORE_DATA_DIR="${MANTICORE_DATA_DIR:-$ROOT_DIR/.podman/gia_manticore_data}"
MANTICORE_LOG_DIR="${MANTICORE_LOG_DIR:-$ROOT_DIR/.podman/gia_manticore_log}"
MANTICORE_MYSQL_PORT="${MANTICORE_MYSQL_PORT:-9306}"
MANTICORE_HTTP_PORT="${MANTICORE_HTTP_PORT:-9308}"
MANTICORE_SPHINX_PORT="${MANTICORE_SPHINX_PORT:-9312}"

mkdir -p "$MANTICORE_DATA_DIR" "$MANTICORE_LOG_DIR"

up() {
  podman run -d \
    --replace \
    --name "$MANTICORE_CONTAINER" \
    -p "${MANTICORE_MYSQL_PORT}:9306" \
    -p "${MANTICORE_HTTP_PORT}:9308" \
    -p "${MANTICORE_SPHINX_PORT}:9312" \
    -v "$MANTICORE_DATA_DIR:/var/lib/manticore" \
    -v "$MANTICORE_LOG_DIR:/var/log/manticore" \
    -v "$MANTICORE_CONFIG_FILE:/etc/manticoresearch/manticore.conf" \
    docker.io/manticoresearch/manticore:latest >/dev/null
  echo "Started $MANTICORE_CONTAINER"
}

down() {
  podman rm -f "$MANTICORE_CONTAINER" >/dev/null 2>&1 || true
  echo "Stopped $MANTICORE_CONTAINER"
}

status() {
  podman ps --format "table {{.Names}}\t{{.Status}}" | grep -E "^$MANTICORE_CONTAINER\b" || true
}

logs() {
  podman logs -f "$MANTICORE_CONTAINER"
}

case "${1:-}" in
  up)
    up
    ;;
  down)
    down
    ;;
  restart)
    down
    up
    ;;
  status)
    status
    ;;
  logs)
    logs
    ;;
  *)
    echo "Usage: $0 {up|down|restart|status|logs}" >&2
    exit 2
    ;;
esac
