#!/bin/sh
#
# rc.edge-relays - Start/stop the AM·OS socat relays for HAProxy
# (socat runs inside the edge-relay netns)
#

EDGE_NETNS="${EDGE_NETNS:-edge-relay}"
PORT_BASE=10000

edge_start() {
  echo "Starting AM·OS Edge Relays..."
  
  if [ -x /etc/rc.d/rc.tor-edge ]; then
    /etc/rc.d/rc.tor-edge start
  fi

  /usr/sbin/edge-relays.sh

  # Make sure HAProxy (chrooted) and haproxy -c can see the map
  if [ -f /etc/haproxy/edge.map ]; then
    mkdir -p /var/lib/haproxy
    cp -a /etc/haproxy/edge.map /var/lib/haproxy/edge.map
    cp -a /etc/haproxy/edge-backends.cfg /var/lib/haproxy/edge-backends.cfg 2>/dev/null || true
    chown haproxy:haproxy /var/lib/haproxy/edge.map /var/lib/haproxy/edge-backends.cfg 2>/dev/null || true
    chmod 644 /var/lib/haproxy/edge.map /var/lib/haproxy/edge-backends.cfg 2>/dev/null || true
    ln -sf /var/lib/haproxy/edge.map /edge.map
  fi

  if [ -x /etc/rc.d/rc.haproxy ]; then
    /etc/rc.d/rc.haproxy reload 2>/dev/null || true
  fi
}

edge_stop() {
  echo "Stopping AM·OS Edge Relays..."
  
  if ip netns list 2>/dev/null | grep -qw "$EDGE_NETNS"; then
    ip netns exec "$EDGE_NETNS" pkill -f "socat TCP-LISTEN:${PORT_BASE}" 2>/dev/null || true
  fi
  pkill -f "socat TCP-LISTEN:${PORT_BASE}" 2>/dev/null || true
  
  if [ -x /etc/rc.d/rc.tor-edge ]; then
    /etc/rc.d/rc.tor-edge stop
  fi

  rm -f /etc/haproxy/edge-backends.cfg
  : > /etc/haproxy/edge.map
  rm -f /var/lib/haproxy/edge.map /var/lib/haproxy/edge-backends.cfg /edge.map
  
  if [ -x /etc/rc.d/rc.haproxy ]; then
    /etc/rc.d/rc.haproxy stop 2>/dev/null || true
  fi
}

edge_restart() {
  edge_stop
  sleep 1
  edge_start
}

edge_status() {
  if ip netns list 2>/dev/null | grep -qw "$EDGE_NETNS" && \
     ip netns exec "$EDGE_NETNS" pgrep -f "socat TCP-LISTEN:${PORT_BASE}" >/dev/null 2>&1; then
    echo "AM·OS Edge Relays are running (in netns $EDGE_NETNS)."
    ip netns exec "$EDGE_NETNS" pgrep -af "socat TCP-LISTEN:${PORT_BASE}" || true
  else
    echo "AM·OS Edge Relays are stopped."
  fi
}

case "$1" in
  start)   edge_start ;;
  stop)    edge_stop ;;
  restart) edge_restart ;;
  status)  edge_status ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
    ;;
esac

exit 0