#!/usr/bin/env bash

module_description() {
  printf "System Services - enable and start NetworkManager and Bluetooth\n"
}

module_required() { return 0; }
module_should_skip() {
  have systemctl || return 0
  return 1
}

module_prereqs() {
  require systemctl systemd
}

module_main() {
  log_section "System Services"

  local services=("NetworkManager.service" "bluetooth.service")

  if [[ -f "$OMERON_PROJECT_DIR/config/omeron.yaml" ]] && command -v python3 >/dev/null 2>&1; then
    local raw_services
    raw_services="$(python3 -c "
import yaml
with open('$OMERON_PROJECT_DIR/config/omeron.yaml') as f:
    data = yaml.safe_load(f)
svcs = data.get('services', [])
print(' '.join(svcs))
" 2>/dev/null)"

    if [[ -n "$raw_services" ]]; then
      read -ra services <<< "$raw_services"
      for i in "${!services[@]}"; do
        if ! [[ "${services[$i]}" == *".service" ]]; then
          services[$i]="${services[$i]}.service"
        fi
      done
    fi
  fi

  for svc in "${services[@]}"; do
    log_info "Enabling $svc..."
    if sudo_run systemctl enable --now "$svc" >/dev/null 2>&1; then
      log_success "$svc enabled and started"
    else
      log_warn "Failed to enable $svc (may already be running)"
    fi
  done

  log_success "Services configured"
}
