#!/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] [service...]

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

  --build      Rebuild images before starting (docker compose up --build)
  -h, --help   Show this help

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

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

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
