#!/usr/bin/env bash
# Restart by stopping then starting (down + up).
# Use --build to rebuild images before bringing services back up.
source "$(dirname "${BASH_SOURCE[0]}")/common.sh"

usage() {
  cat <<EOF
Usage: ${RUN_CMD:-run-stack} restart [--build] [--essential] [service...]

Stop then start the stack (or the named services).

  --build      Rebuild images before starting (docker compose up --build)
  --essential  Only the services listed under "essential" in run.config.json
  -h, --help   Show this help

Without --build, existing images are reused. Data volumes are kept either way.
EOF
}

build=false
essential=false
services=()
for arg in "$@"; do
  case "${arg}" in
    --build) build=true ;;
    --essential) essential=true ;;
    -h|--help)
      usage
      exit 0
      ;;
    -*)
      echo "error: unknown option: ${arg}" >&2
      usage >&2
      exit 1
      ;;
    *) services+=("${arg}") ;;
  esac
done

if [ "${essential}" = true ]; then
  if [ "${#services[@]}" -gt 0 ]; then
    echo "error: pass service names or --essential, not both" >&2
    exit 1
  fi
  ensure_essential_config
  while IFS= read -r name; do
    [ -n "${name}" ] || continue
    services+=("${name}")
  done < <(essential_service_names)
  if [ "${#services[@]}" -eq 0 ]; then
    echo "error: no essential services configured — add them under \"essential\" in ${WORKSPACE_CONFIG}" >&2
    exit 1
  fi
fi

scripts="$(dirname "${BASH_SOURCE[0]}")"
bash "${scripts}/down.sh" "${services[@]}"
if [ "${build}" = true ]; then
  RUN_UP_BUILD=1 bash "${scripts}/up.sh" "${services[@]}"
else
  RUN_UP_BUILD=0 bash "${scripts}/up.sh" "${services[@]}"
fi
