#!/usr/bin/env bash
# Passwordless sudo for edge bridge launcher (supervisor runs as topbox).
#   sudo bash install_edge_sudoers.sh

set -euo pipefail

if [[ "${EUID}" -ne 0 ]]; then
  echo "FATAL: run with sudo" >&2
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ -f "${SCRIPT_DIR}/../sync/ethergold_paths.sh" ]]; then
  # shellcheck source=../sync/ethergold_paths.sh
  source "${SCRIPT_DIR}/../sync/ethergold_paths.sh"
else
  ETHERGOLD_RUNTIME="${ETHERGOLD_RUNTIME:-/home/topbox/EtherGold/prod}"
fi

RUNTIME="${ETHERGOLD_RUNTIME:-${ETHERGOLD_DAEMON:-/home/topbox/EtherGold/prod}}"
UNIFIED_SCRIPT="${RUNTIME}/run_ethergold.sh"
EDGE_SCRIPT="${RUNTIME}/run_bridge_edge_prod.sh"
LED_SCRIPT="${RUNTIME}/ethergold_status_led.sh"
SUDOERS="/etc/sudoers.d/ethergold"

if [[ ! -f "${UNIFIED_SCRIPT}" ]]; then
  UNIFIED_SCRIPT="${SCRIPT_DIR}/run_ethergold.sh"
fi
if [[ ! -f "${EDGE_SCRIPT}" ]]; then
  EDGE_SCRIPT="${SCRIPT_DIR}/run_bridge_edge_prod.sh"
fi
if [[ ! -f "${LED_SCRIPT}" ]]; then
  LED_SCRIPT="${SCRIPT_DIR}/ethergold_status_led.sh"
fi
if [[ ! -f "${LED_SCRIPT}" ]]; then
  LED_SCRIPT="${SCRIPT_DIR}/fixture_status_led.sh"
fi

cat > "${SUDOERS}" <<EOF
# EtherGold — supervisor helpers (no password prompt).
topbox ALL=(root) NOPASSWD: ${UNIFIED_SCRIPT}
topbox ALL=(root) NOPASSWD: ${EDGE_SCRIPT}
topbox ALL=(root) NOPASSWD: ${LED_SCRIPT}
EOF
chmod 440 "${SUDOERS}"
visudo -cf "${SUDOERS}"
echo "Installed ${SUDOERS}"
