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

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMPOSE_FILE="${PROJECT_ROOT}/deploy/docker/docker-compose.yml"

SDR_UNITS=(
  dronedetector-sdr-433.service
  dronedetector-sdr-750.service
  dronedetector-sdr-1500.service
  dronedetector-sdr-3300.service
  dronedetector-sdr-4500.service
  dronedetector-sdr-5200.service
  dronedetector-sdr-5800.service
  dronedetector-sdr-915.service
  dronedetector-sdr-1200.service
  dronedetector-sdr-2400.service
)

CONFIGURED_SDR_UNITS=()

log() {
  printf '[restart_all] %s\n' "$*"
}

sdr_unit_env_key() {
  local unit="$1"
  local band="${unit#dronedetector-sdr-}"
  band="${band%.service}"
  printf 'hack_%s\n' "$band"
}

get_env_value() {
  local key="$1"
  awk -F= -v key="$key" '
    $1 == key {
      value = substr($0, index($0, "=") + 1)
      sub(/^[[:space:]]+/, "", value)
      sub(/[[:space:]]+$/, "", value)
      gsub(/^"/, "", value)
      gsub(/"$/, "", value)
      gsub(/^'\''/, "", value)
      gsub(/'\''$/, "", value)
      print value
      exit
    }
  ' "${PROJECT_ROOT}/.env"
}

populate_configured_sdr_units() {
  CONFIGURED_SDR_UNITS=()

  local unit env_key env_value
  for unit in "${SDR_UNITS[@]}"; do
    env_key="$(sdr_unit_env_key "$unit")"
    env_value="$(get_env_value "$env_key")"
    if [[ -n "$env_value" ]]; then
      CONFIGURED_SDR_UNITS+=("$unit")
    else
      log "Skipping ${unit}: ${env_key} is empty in .env"
    fi
  done
}

if [[ -x /usr/bin/sudo ]]; then
  SUDO=(sudo)
else
  SUDO=()
fi

restart_docker_services() {
  log "Restarting Docker services (without build)"

  if [[ -f "$COMPOSE_FILE" ]]; then
    docker compose -f "$COMPOSE_FILE" up -d
  else
    log "Compose file not found: $COMPOSE_FILE"
  fi
}

restart_sdr_services() {
  log "Restarting SDR systemd units"
  for unit in "${CONFIGURED_SDR_UNITS[@]}"; do
    ${SUDO[@]} systemctl restart "$unit"
  done
}

print_status() {
  log "Docker status"
  docker compose -f "$COMPOSE_FILE" ps || true

  log "SDR status"
  for unit in "${CONFIGURED_SDR_UNITS[@]}"; do
    if ${SUDO[@]} systemctl is-active --quiet "$unit"; then
      printf '%s: active\n' "$unit"
    else
      printf '%s: NOT active\n' "$unit"
    fi
  done
}

main() {
  populate_configured_sdr_units
  restart_docker_services
  restart_sdr_services
  print_status
  log "Done"
}

main "$@"
