#!/bin/sh
#
# tor - The Onion Router (Edge relay instance)
#
# Edge edition: this Tor runs inside the edge-relay netns and is placed
# in /sys/fs/cgroup/edge/tor. It is the Tor used by the SNI relay
# (HAProxy → socat → this Tor). It is distinct from any host-side
# system Tor that netmode may start for open mode.
#
# Not started at boot by default; start it explicitly (or from your
# Edge relay startup) after the netns exists.

if [ -r /proc/sys/fs/file-max ]; then
  SYSTEM_MAX=`cat /proc/sys/fs/file-max`
  if [ "$SYSTEM_MAX" -gt "80000" ]; then
    MAX_FILEDESCRIPTORS=32768
  elif [ "$SYSTEM_MAX" -gt "40000" ]; then
    MAX_FILEDESCRIPTORS=16384
  elif [ "$SYSTEM_MAX" -gt "10000" ]; then
    MAX_FILEDESCRIPTORS=8192
  else
    MAX_FILEDESCRIPTORS=1024
    cat << EOF

Warning: Your system has very few filedescriptors available in total.

Maybe you should try raising that by adding 'fs.file-max=100000' to your
/etc/sysctl.conf file.  Feel free to pick any number that you deem appropriate.
Then run 'sysctl -p'.  See /proc/sys/fs/file-max for the current value, and
file-nr in the same directory for how many of those are used at the moment.

EOF
  fi
else
  MAX_FILEDESCRIPTORS=8192
fi

EDGE_NETNS="${EDGE_NETNS:-edge-relay}"
EDGE_TOR_CGROUP="/sys/fs/cgroup/edge/tor"
EDGE_PIDFILE="/var/run/tor/tor-edge.pid"
EDGE_LOG="/var/log/tor/edge-notices.log"

EDGE_CONTROL_PORT=9051
EDGE_COOKIE="/var/lib/tor-edge/control_auth_cookie"   # adjust if your DataDirectory differs

EDGE_WATCH_PIDFILE="/var/run/tor/edge-watch.pid"
EDGE_HEALTH_LOCK="/var/run/tor/edge-health.lock"

tor_watch() {
  if [ -r "$EDGE_WATCH_PIDFILE" ] && kill -0 "$(cat "$EDGE_WATCH_PIDFILE")" 2>/dev/null; then
    return 0
  fi
  (
    while true; do
      sleep 30
      # Do not re-enter if a restart is already in progress
      if [ ! -f "$EDGE_HEALTH_LOCK" ]; then
        tor_health
      fi
    done
  ) >/dev/null 2>&1 &
  echo $! > "$EDGE_WATCH_PIDFILE"
}

tor_watch_stop() {
  if [ -r "$EDGE_WATCH_PIDFILE" ]; then
    kill "$(cat "$EDGE_WATCH_PIDFILE")" 2>/dev/null || true
    rm -f "$EDGE_WATCH_PIDFILE"
  fi
  rm -f "$EDGE_HEALTH_LOCK"
}

tor_health() {
  local phase

  # Simple lock so we never nest restarts
  if [ -f "$EDGE_HEALTH_LOCK" ]; then
    return 0
  fi
  touch "$EDGE_HEALTH_LOCK"

  phase=$(ip netns exec "$EDGE_NETNS" \
    sh -c "printf 'AUTHENTICATE %s\r\nGETINFO status/bootstrap-phase\r\nQUIT\r\n' \
          \"\$(xxd -p '$EDGE_COOKIE' | tr -d '\n')\" \
          | nc -w 3 127.0.0.1 $EDGE_CONTROL_PORT" 2>/dev/null \
    | sed -n 's/.*BOOTSTRAP PROGRESS=\([0-9]*\).*/\1/p' | head -1)

  if [ "$phase" = "100" ]; then
    rm -f "$EDGE_HEALTH_LOCK"
    return 0
  fi

  echo "$(date): Edge Tor bootstrap at ${phase:-unknown}%, restarting" >> /var/log/tor/edge-health.log
  tor_watch_stop          # stop the old watcher first
  tor_stop
  sleep 3
  tor_start               # this starts a fresh watcher
  rm -f "$EDGE_HEALTH_LOCK"
  return $?
}


ensure_logs() {
  mkdir -p /var/log/tor /var/run/tor
  chown tor:tor /var/log/tor /var/run/tor
  chmod 755 /var/log/tor /var/run/tor

  touch "$EDGE_LOG"
  chown tor:tor "$EDGE_LOG"
  chmod 644 "$EDGE_LOG"
}

ensure_netns() {
  if ! ip netns list 2>/dev/null | grep -qw "$EDGE_NETNS"; then
    echo "Tor: netns $EDGE_NETNS missing; run 'netmode strict' first" >&2
    return 1
  fi
  return 0
}

tor_start() {
  ensure_logs
  mkdir -p /var/run/tor
  chown tor:tor /var/run/tor

  ensure_netns || return 1

  mkdir -p "$EDGE_TOR_CGROUP" 2>/dev/null || true

  if [ -n "$MAX_FILEDESCRIPTORS" ]; then
    echo -n "Raising maximum number of filedescriptors (ulimit -n) to $MAX_FILEDESCRIPTORS"
    if ulimit -n "$MAX_FILEDESCRIPTORS" ; then
      echo "..."
    else
      echo ": FAILED."
    fi
  fi


  echo "Starting Tor in netns $EDGE_NETNS..."
  # clean-exec closes fd 255, avoiding AppArmor denials.
  # Tor handles its own backgrounding via RunAsDaemon 1 in torrc.edge.
  if clean-exec ip netns exec "$EDGE_NETNS" /usr/bin/tor -f /etc/tor/torrc.edge; then
    # Give it a moment to write the PID file
    sleep 0.5
    if [ -r "$EDGE_PIDFILE" ] && kill -0 "$(cat "$EDGE_PIDFILE" 2>/dev/null)" 2>/dev/null; then
      # Place in cgroup
      if [ -d "$EDGE_TOR_CGROUP" ]; then
        echo "$(cat "$EDGE_PIDFILE")" > "$EDGE_TOR_CGROUP/cgroup.procs" 2>/dev/null || true
      fi
      echo "Tor started (PID $(cat "$EDGE_PIDFILE"))."
    else
      echo "Tor failed to start (no PID file)." >&2
      return 1
    fi
  else
    echo "Tor failed to launch." >&2
    return 1
  fi
  tor_watch
}

tor_stop() {
  tor_watch_stop
  echo -n "Stopping Tor..."
  PID=`cat $EDGE_PIDFILE 2>/dev/null`
  if [ -z "$PID" ]; then
    echo " not running."
    return 0
  fi
  if kill -15 $PID 2>/dev/null; then
    echo " stopped."
  else
    sleep 1
    if kill -9 $PID 2>/dev/null; then
      echo " killed."
    else
      echo " error!"
      return 1
    fi
  fi
}

tor_reload() {
  echo -n "Reloading Tor..."
  PID=`cat $EDGE_PIDFILE 2>/dev/null`
  if [ -z "$PID" ]; then
    echo " not running."
    return 0
  fi
  if kill -1 $PID 2>/dev/null; then
    echo " reloaded."
  else
    echo " error!"
    return 1
  fi
}

tor_status() {
  PID=`cat $EDGE_PIDFILE 2>/dev/null`
  if [ -z "$PID" ]; then
    echo "Not running."
    return 1
  elif kill -0 $PID 2>/dev/null; then
    if ip netns identify $PID 2>/dev/null | grep -qw "$EDGE_NETNS"; then
      echo "Running (in netns $EDGE_NETNS)."
    else
      echo "Running (PID $PID) but not in netns $EDGE_NETNS."
    fi
    return 0
  else
    echo "PID file $EDGE_PIDFILE present but PID $PID is not running."
    return 1
  fi
}

case "$1" in
  start)   tor_start ;;
  stop)    tor_stop ;;
  restart) tor_stop; sleep 3; tor_start ;;
  reload)  tor_reload ;;
  status)  tor_status ;;
  health) tor_health ;;
  *) echo "Usage: $0 (start|stop|restart|reload|status|health)" ;;
esac