#!/bin/bash
#
# AMOS initialization script for HAProxy (Edge edition).
# Starts HAProxy inside the edge-relay netns and places it in /edge/haproxy.
#
# Close high fds (including the interactive-shell scratch fd 255) so no
# command launched from this script inherits the parent's terminal.
exec 3>&- 4>&- 5>&- 6>&- 7>&- 8>&- 9>&- 255>&-

HAPROXY=/usr/sbin/haproxy
CONFIG=/etc/haproxy/haproxy.cfg
PIDFILE=/run/haproxy.pid

EDGE_NETNS="${EDGE_NETNS:-edge-relay}"
EDGE_HAPROXY_CGROUP="/sys/fs/cgroup/edge/haproxy"

if [[ ! -f $CONFIG && "$1" == "start" ]]; then
   echo "No configuration file found. Cannot continue."
   echo "The script looks for the configuration file placed in $CONFIG"
   exit 1
fi

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

start() {
    if [ -r $PIDFILE ]; then
        echo 'HAProxy is already running!'
        return
    fi

    ensure_netns || return 1
    
    # Config check runs on the host and looks for the path written in the cfg (/edge.map).
    # Provide a temporary view of the real file so -c succeeds; the chrooted process
    # will see the same file at /edge.map inside /var/lib/haproxy.
    if [ -f /var/lib/haproxy/edge.map ]; then
    ln -sfn /var/lib/haproxy/edge.map /edge.map
    fi

    # Reject a broken config early
    if ! clean-exec-sync $HAPROXY -c -q -f $CONFIG </dev/null >/dev/null 2>&1; then
        echo "HAProxy: configuration error in $CONFIG (refusing to start)" >&2
        return 1
    fi

    
    echo "Starting HAProxy in netns $EDGE_NETNS..."
    clean-exec ip netns exec "$EDGE_NETNS" "$HAPROXY" \
    -f "$CONFIG" -f /etc/haproxy/edge-backends.cfg \
    -D -p "$PIDFILE"

    # Move the process into the haproxy cgroup (PID file is written on the host)
    if [ -r $PIDFILE ] && [ -d "$EDGE_HAPROXY_CGROUP" ]; then
      local pid
      pid=$(cat $PIDFILE 2>/dev/null)
      if [ -n "$pid" ]; then
        echo "$pid" > "$EDGE_HAPROXY_CGROUP/cgroup.procs" 2>/dev/null || true
      fi
    fi
}

reload() {
    if [ ! -r $PIDFILE ]; then
        echo "HAProxy is not running; starting instead..."
        start
        return
    fi
    local oldpid
    oldpid=$(cat $PIDFILE)
    echo "Reloading HAProxy..."
    clean-exec ip netns exec "$EDGE_NETNS" "$HAPROXY" \
    -f "$CONFIG" -f /etc/haproxy/edge-backends.cfg \
    -D -p $PIDFILE -sf "$oldpid"
    # Re-apply cgroup (new PID)
    if [ -r $PIDFILE ] && [ -d "$EDGE_HAPROXY_CGROUP" ]; then
        echo "$(cat $PIDFILE)" > "$EDGE_HAPROXY_CGROUP/cgroup.procs" 2>/dev/null || true
    fi
}

stop() {
    if [ ! -r $PIDFILE ]; then
        echo 'HAProxy is not running!'
        return
    fi
    echo "Soft-stopping HAProxy..."
    # Signal works from the host even if the process is in a netns
    kill -USR1 $(cat $PIDFILE) 2>/dev/null || true
    rm -f $PIDFILE
}

force_stop() {
    if [ ! -r $PIDFILE ]; then
        echo 'HAProxy is not running!'
        return
    fi
    echo "Hard-stopping HAProxy..."
    kill $(cat $PIDFILE) 2>/dev/null || true
    rm -f $PIDFILE
}

status() {
    if [ ! -r $PIDFILE ]; then
        echo "HAProxy is not running."
        return
    fi
    PID=$(cat $PIDFILE)
    if [ -z "$PID" ]; then
        echo 'PID file is empty! HAProxy does not appear to be running, but there is a stale PID file.'
    elif kill -0 $PID 2>/dev/null; then
        # Confirm it is inside the expected netns
        if ip netns identify $PID 2>/dev/null | grep -qw "$EDGE_NETNS"; then
          echo "HAProxy is running (in netns $EDGE_NETNS)."
        else
          echo "HAProxy is running (PID $PID) but not in netns $EDGE_NETNS."
        fi
    else
        echo "HAProxy is not running, but there is a stale PID file."
    fi
}

case "$1" in
    'start')
        start
        ;;
    'stop')
        stop
        ;;
    'reload')
        reload
        ;;
    'force_stop')
        force_stop
        ;;
    'restart')
        stop
        sleep 0.5
        start
        ;;
    'force_restart')
        force_stop
        sleep 0.5
        start
        ;;
    'status')
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|force_stop|reload|restart|force_restart|status}"
        exit 1
        ;;
esac
