#!/bin/bash
set -euo pipefail

# Print status of relevant services and warn if mutually exclusive ones are running.
# Utilities (network audio):
#   - ptp_aes67.service (system)
#   - pipewire-aes67.service (user)
# App services (mutually exclusive groups):
#   - auracast-script.service (user)
#   - auracast-server.service (prefer user; also check system)
#   - auracast-frontend.service (system)

print_status() {
  local scope="$1"  # "system" or "user"
  local unit="$2"
  local act="unknown"
  local ena="unknown"
  if [[ "$scope" == "user" ]]; then
    act=$(systemctl --user is-active "$unit" 2>/dev/null || true)
    ena=$(systemctl --user is-enabled "$unit" 2>/dev/null || true)
  else
    act=$(systemctl is-active "$unit" 2>/dev/null || true)
    ena=$(systemctl is-enabled "$unit" 2>/dev/null || true)
  fi
  act="${act:-unknown}"
  ena="${ena:-unknown}"
  printf " - %-24s [%s] active=%-10s enabled=%s\n" "$unit" "$scope" "$act" "$ena"
}

is_active() {
  local scope="$1" unit="$2"
  if [[ "$scope" == "user" ]]; then
    systemctl --user is-active "$unit" &>/dev/null && echo yes || echo no
  else
    systemctl is-active "$unit" &>/dev/null && echo yes || echo no
  fi
}

hr() { printf '\n%s\n' "----------------------------------------"; }

printf "AURACAST SERVICE STATUS\n"
hr

printf "Utilities (required for network audio)\n"
print_status system ptp_aes67.service
print_status user   pipewire-aes67.service

PTP_ACTIVE=$(is_active system ptp_aes67.service)
PW_ACTIVE=$(is_active user   pipewire-aes67.service)

if [[ "$PTP_ACTIVE" == "yes" && "$PW_ACTIVE" == "yes" ]]; then
  echo " ✓ Utilities ready for AES67/network audio"
else
  echo " ! Utilities not fully active (AES67/network audio may not work)"
fi

hr
printf "Application services (mutually exclusive)\n"
print_status user   auracast-script.service
print_status user   auracast-server.service
print_status system auracast-server.service
print_status system auracast-frontend.service

SCRIPT_ACTIVE=$(is_active user   auracast-script.service)
SERVER_USER_ACTIVE=$(is_active user   auracast-server.service)
SERVER_SYS_ACTIVE=$(is_active system auracast-server.service)
FRONT_ACTIVE=$(is_active system auracast-frontend.service)

# Consider server active if either user or system instance is active
if [[ "$SERVER_USER_ACTIVE" == "yes" || "$SERVER_SYS_ACTIVE" == "yes" ]]; then
  SERVER_ACTIVE=yes
else
  SERVER_ACTIVE=no
fi

if [[ "$SCRIPT_ACTIVE" == "yes" && ( "$SERVER_ACTIVE" == "yes" || "$FRONT_ACTIVE" == "yes" ) ]]; then
  echo " ! WARNING: 'auracast-script' and 'server/frontend' are running together (mutually exclusive)."
fi

hr
printf "Hints\n"
echo " - Follow logs (user): journalctl --user -u auracast-script.service -f"
echo " - Follow logs (server): journalctl --user -u auracast-server.service -f || journalctl -u auracast-server.service -f"
echo " - Frontend logs: journalctl -u auracast-frontend.service -f"
