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

INSTANCE="${ATHENA_LIMA_INSTANCE:-athenaos}"
CONFIG_URL="${ATHENA_LIMA_CONFIG_URL:-https://apt.athena-os.org/macos/athenaos-lima.yaml}"
CONFIG_FILE="${TMPDIR:-/tmp}/athenaos-lima.yaml"

if ! command -v limactl >/dev/null 2>&1; then
  if command -v brew >/dev/null 2>&1; then
    brew install lima
  else
    echo "Lima is required. Install Homebrew, then run: brew install lima" >&2
    exit 1
  fi
fi

curl -fsSL "${CONFIG_URL}" -o "${CONFIG_FILE}"

if limactl list --format '{{.Name}}' 2>/dev/null | grep -qx "${INSTANCE}"; then
  echo "Lima instance '${INSTANCE}' already exists."
  echo "Open it with: limactl shell ${INSTANCE}"
  exit 0
fi

limactl start --name "${INSTANCE}" "${CONFIG_FILE}"
limactl shell "${INSTANCE}" athena version

cat <<EOF
AthenaOS macOS VM is ready.

Open it with:
  limactl shell ${INSTANCE}

Verify:
  athena self-test
EOF
