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

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"

if [[ "$(uname -s)" != "Linux" ]]; then
  printf 'Fel: OpenDartboard x86 stöder endast Linux.\n' >&2
  exit 1
fi

case "$(uname -m)" in
  x86_64|amd64) ;;
  *)
    printf 'Fel: en 64-bitars x86_64/amd64-dator krävs.\n' >&2
    exit 1
    ;;
esac

if ! command -v docker >/dev/null 2>&1; then
  printf 'Fel: Docker med Compose-tillägget måste installeras först.\n' >&2
  exit 1
fi

if ! docker compose version >/dev/null 2>&1; then
  printf 'Fel: kommandot "docker compose" saknas.\n' >&2
  exit 1
fi

mkdir -p "$script_dir/data"
docker compose --project-directory "$script_dir" -f "$script_dir/docker-compose.yml" up --build --detach

health="starting"
for ((attempt = 1; attempt <= 30; attempt++)); do
  health="$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' opendartboard-x86 2>/dev/null || true)"
  if [[ "$health" == "healthy" ]]; then
    break
  fi
  if [[ "$health" == "exited" || "$health" == "dead" || "$health" == "unhealthy" ]]; then
    break
  fi
  sleep 1
done

if [[ "$health" != "healthy" ]]; then
  printf 'Fel: servern blev inte redo (status: %s).\n' "$health" >&2
  docker compose --project-directory "$script_dir" -f "$script_dir/docker-compose.yml" logs --tail 40 >&2
  exit 1
fi

printf '\nOpenDartboard x86 är startad.\n'
printf 'Öppna: http://localhost:%s\n' "${OPENDARTBOARD_PORT:-13520}"
printf 'Status: docker compose -f %s/docker-compose.yml ps\n' "$script_dir"
