#!/bin/sh
# sigma-agent-setup -- configure the SigmaSRC agent.
#
# Single source of truth for writing conf/config (central server + poliwall
# enforcement) and conf/enterprise. Used by the RPM %post, the Debian postinst
# (with debconf-supplied values), and by an admin at any time to reconfigure.
#
# Usage:
#   sigma-agent-setup                interactive reconfigure (whiptail or read)
#   sigma-agent-setup --install      install-time: prompt if a TTY is present,
#                                     otherwise apply env/defaults or print a
#                                     "not configured" notice (never blocks)
#   sigma-agent-setup --batch        non-interactive: use env/flags only
#
# Values (flag overrides env):
#   --server H      / CSERVER=H            ESP server address (required)
#   --enforce y|n   / PW_ENFORCE=true|false  enforce poliwall (default: false)
#   --enterprise y|n/ ESI_ENTERPRISE=enterprise  enterprise install (default: no)
set -eu

AGENT_DIR="${AVROOT:-/opt/sigma/agent}"
CONF="${AGENT_DIR}/conf/config"
ENT="${AGENT_DIR}/conf/enterprise"
TPL="${AGENT_DIR}/active/scripts/etc/sigma_agent_config.tpl"
PLACEHOLDER="qali01"

MODE=interactive
SERVER="${CSERVER:-}"
ENFORCE="${PW_ENFORCE:-}"
ENTERPRISE="${ESI_ENTERPRISE:-}"

while [ $# -gt 0 ]; do
    case "$1" in
        --install)    MODE=install ;;
        --batch)      MODE=batch ;;
        --server)     SERVER="${2:-}"; shift ;;
        --enforce)    ENFORCE="${2:-}"; shift ;;
        --enterprise) ENTERPRISE="${2:-}"; shift ;;
        -h|--help)    sed -n '2,20p' "$0"; exit 0 ;;
        *) echo "sigma-agent-setup: unknown argument '$1'" >&2; exit 2 ;;
    esac
    shift
done

have_tty() { [ -t 0 ] && [ -t 1 ]; }

# Host portion of the currently-configured central-server (empty if none).
current_server() {
    [ -f "$CONF" ] || return 0
    sed -n 's/^[[:space:]]*central-server[[:space:]]*=[[:space:]]*\([^:[:space:]]*\).*/\1/p' "$CONF" | head -1
}

bool() {  # y/yes/true/1/on/enforce -> true, anything else -> false
    case "$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')" in
        y|yes|true|1|on|enforce) echo true ;;
        *) echo false ;;
    esac
}

notice() {
    cat >&2 <<EOF
============================================================================
  SigmaSRC Agent is NOT configured yet (no central server set).
  Configure it with:   sudo sigma-agent-setup
  The agent will not start until a central server is configured.
============================================================================
EOF
}

# In install mode: skip entirely if already configured; treat a supplied server
# (env/preseed) as a batch apply.
if [ "$MODE" = install ]; then
    cs="$(current_server)"
    if [ -n "$cs" ] && [ "$cs" != "$PLACEHOLDER" ]; then exit 0; fi
    [ -n "$SERVER" ] && MODE=batch
fi

# Collect values interactively when asked to (or at install time on a TTY).
if [ "$MODE" = interactive ] || { [ "$MODE" = install ] && [ -z "$SERVER" ] && have_tty; }; then
    if have_tty && command -v whiptail >/dev/null 2>&1; then
        SERVER=$(whiptail --title "Sigma Agent Setup" --inputbox \
            "ESP server address this agent should report to:" 9 70 "$SERVER" 3>&1 1>&2 2>&3) || exit 1
        if whiptail --title "Sigma Agent Setup" --defaultno --yesno \
            "Enforce poliwall packet filtering on this host?\n\nOff by default. Enable only if this host should enforce network packet-filtering rules." 11 70
        then ENFORCE=true; else ENFORCE=false; fi
        if whiptail --title "Sigma Agent Setup" --defaultno --yesno \
            "Is this an enterprise install (enable enterprise-only compliance rules)?" 9 70
        then ENTERPRISE=enterprise; else ENTERPRISE=; fi
    elif have_tty; then
        printf 'ESP server address this agent should report to: '; read SERVER < /dev/tty
        printf 'Enforce poliwall packet filtering on this host? [y/N]: '; read a < /dev/tty; ENFORCE="$(bool "$a")"
        printf 'Enterprise install? [y/N]: '; read a < /dev/tty
        if [ "$(bool "$a")" = true ]; then ENTERPRISE=enterprise; else ENTERPRISE=; fi
    else
        notice; exit 0
    fi
fi

ENFORCE="$(bool "${ENFORCE:-false}")"

if [ -z "$SERVER" ]; then notice; exit 0; fi

# Write conf/config from the template.
mkdir -p "${AGENT_DIR}/conf"
[ -f "$TPL" ] || { echo "sigma-agent-setup: template $TPL not found" >&2; exit 1; }
sed -e "s#${PLACEHOLDER}#${SERVER}#" \
    -e "s#\(poliwall-enforce =\).*#\1 ${ENFORCE}#" \
    "$TPL" > "${CONF}.new"
mv "${CONF}.new" "$CONF"
chmod go= "$CONF" 2>/dev/null || true
echo "sigma-agent-setup: wrote $CONF (server=$SERVER, poliwall-enforce=$ENFORCE)"

case "$(bool "$ENTERPRISE")$ENTERPRISE" in
    *enterprise*|true*) : > "$ENT"; echo "sigma-agent-setup: enterprise mode enabled" ;;
    *) rm -f "$ENT" ;;
esac

# (Re)start the service via systemd (native unit) when present, else the init
# script. No-op at install time if neither is registered yet -- the package's
# post-install starts it after registration.
SVC="${AGENT_DIR}/active/scripts/sigma-agent-svc"
if [ -f "$SVC" ]; then
    sh "$SVC" restart >/dev/null 2>&1 || sh "$SVC" start >/dev/null 2>&1 || true
elif [ -x /etc/init.d/sigma_agent ]; then
    /etc/init.d/sigma_agent restart >/dev/null 2>&1 || true
fi
exit 0
