#!/usr/bin/env bash
# =============================================================================
# with-docker.sh — run Trakop in containers.
#
#     run/with-docker.sh                    cut over to Docker (containers own :80)
#     run/with-docker.sh --dry-run          show every action, change nothing
#     run/with-docker.sh --keep-host-apache legacy: move host Apache to :8080
#
# AFTER this runs:
#     http://localhost         -> trakop-cakephp container
#     http://127.0.0.1:8082    -> Adminer (the database client)
#     host apache2/php7.4-fpm  -> stopped and disabled
#     TrakopLens               -> retrieves via pgvector + Ollama (AI embeddings)
#
# A thin wrapper around docker/scripts/start-docker.sh. What it adds: the sudo
# escalation, the health check afterwards, and freeing :8400 first — see below.
# =============================================================================
set -uo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1
REPO_ROOT="$(pwd)"

G=$'\033[32m'; R=$'\033[31m'; Y=$'\033[33m'; B=$'\033[1m'; N=$'\033[0m'

DRY=0
for a in "$@"; do [ "$a" = "--dry-run" ] && DRY=1; done

# The container infrastructure is deliberately NOT tracked in git (see run/README.md), so
# a deployment cloned from the repo has no docker/ directory at all. Say that plainly
# instead of failing on a missing path three lines later, because on such a server the
# answer is not "fix the script" — it is "this box is host-only, and that is by design".
if [ ! -x "$REPO_ROOT/docker/scripts/start-docker.sh" ]; then
    printf "${R}Docker mode is not available on this machine.${N}\n"
    printf "  %s/docker/ is missing — the container files are not part of the repository.\n" "$REPO_ROOT"
    printf "  This box runs Trakop WITHOUT Docker, which needs nothing extra:\n"
    printf "    run/status.sh            what is running now\n"
    printf "    run/without-docker.sh    (re)apply host mode\n"
    exit 2
fi

# Taking :80 from host Apache stops and disables systemd units, so this needs root.
if [ "$DRY" = 0 ] && [ "$(id -u)" -ne 0 ]; then
    printf "${Y}switching to Docker mode needs root — re-running under sudo${N}\n"
    exec sudo -- "$0" "$@"
fi

# THE ONE THING start-docker.sh CANNOT KNOW ABOUT. Host mode may be serving realtime
# tracking from ops/trakop-node.service, and the `node` container binds the same :8400.
# Whichever starts second dies with EADDRINUSE, so the host unit is stopped FIRST —
# otherwise the container comes up unhealthy and the cause is three layers down a log.
if [ "$(systemctl is-active trakop-node 2>/dev/null)" = "active" ]; then
    if [ "$DRY" = 1 ]; then
        printf "  [dry-run] systemctl stop trakop-node   (frees :8400 for the container)\n"
    else
        printf "${Y}stopping the host trakop-node unit — the container needs :8400${N}\n"
        systemctl stop trakop-node
    fi
fi

"$REPO_ROOT/docker/scripts/start-docker.sh" "$@" || exit $?

[ "$DRY" = 1 ] && exit 0

# As in without-docker.sh: run the checks as the invoking user so nothing in the app's
# cache or log directories ends up owned by root.
printf "\n${B}=== VERIFYING THE STACK ===${N}\n"
RUN_AS=(); [ -n "${SUDO_USER:-}" ] && RUN_AS=(sudo -u "$SUDO_USER")
"${RUN_AS[@]}" "$REPO_ROOT/docker/scripts/verify-stack.sh"
RC=$?

printf "\n${B}Back to host mode:${N} run/without-docker.sh\n\n"
exit "$RC"
