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

home_dir="${HOME:?HOME is required}"
data_home="${XDG_DATA_HOME:-$home_dir/.local/share}"
config_home="${XDG_CONFIG_HOME:-$home_dir/.config}"
app_root="$data_home/vimatee/current"
runtime_env="$config_home/vimatee/runtime.env"
export VIMATEE_ENV_FILE="$runtime_env"

[[ -d "$app_root" ]] || { printf 'Vimatee is not installed under %s\n' "$data_home/vimatee" >&2; exit 1; }
[[ -f "$runtime_env" ]] || { printf 'Missing Vimatee configuration: %s\n' "$runtime_env" >&2; exit 1; }
compose_project="$(sed -n 's/^VIMATEE_COMPOSE_PROJECT=//p' "$runtime_env" | tail -1)"
compose_project="${compose_project:-vimatee}"
compose=(docker compose --project-name "$compose_project" --env-file "$runtime_env" -f "$app_root/compose.yaml")

case "${1:-status}" in
  install)
    shift
    cd "$app_root"
    exec env VIMATEE_ENV_FILE="$runtime_env" ./scripts/install-local.sh "$@"
    ;;
  up|start)
    shift
    exec "${compose[@]}" up -d "$@"
    ;;
  stop)
    shift
    exec "${compose[@]}" stop "$@"
    ;;
  status)
    curl -fsS http://127.0.0.1:8080/healthz >/dev/null
    "${compose[@]}" ps
    ;;
  logs)
    shift
    exec "${compose[@]}" logs "$@"
    ;;
  config)
    exec "${compose[@]}" config --quiet
    ;;
  *)
    printf 'Usage: vimatee {install|up|start|stop|status|logs|config}\n' >&2
    exit 2
    ;;
esac
