#!/usr/bin/env bash
# rita.sh - install/remove RITA v5 (vendor container stack) under PODMAN
# on Debian 13 (trixie). The vendor ships RITA v5 only as a container stack
# (rita API + ClickHouse + syslog-ng); there is no native build, so per the
# owner's rule this installs the containers with podman, not docker.
# Usage: sudo ./rita.sh add|remove|status

set -euo pipefail

RITA_VERSION=5.1.2
TARBALL_URL="https://github.com/activecm/rita/releases/download/v${RITA_VERSION}/rita-v${RITA_VERSION}.tar.gz"
BIN=/usr/local/bin/rita
OPT_RITA=/opt/rita
ETC_RITA=/etc/rita
COMPOSE=${OPT_RITA}/docker-compose.yml
RITA_CONTAINER=rita-rita-1
ZEEK_LOGS=/opt/zeek/logs
# Same IFACE convention/validation as the other tool scripts.
IFACE="${IFACE:-eth0}"
[[ $IFACE =~ ^[A-Za-z0-9._@:-]+$ ]] || { echo "invalid IFACE" >&2; exit 1; }

# Re-exec with sudo if not root
if [[ ${EUID} -ne 0 ]]; then
    exec sudo -E "$0" "$@"
fi

usage() {
    echo "Usage: $0 {add|remove|status}"
    exit 2
}

compose() {
    podman-compose -f "${COMPOSE}" "$@"
}

rita_network() {
    podman inspect "${RITA_CONTAINER}" --format \
        '{{range $k,$v := .NetworkSettings.Networks}}{{$k}}{{end}}' 2>/dev/null
}

add() {
    echo "[*] Installing podman + podman-compose (Debian main)"
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -y || true
    apt-get install -y podman podman-compose

    echo "[*] Downloading rita-v${RITA_VERSION}.tar.gz"
    TMP_TGZ=$(mktemp /tmp/rita-XXXXXX.tar.gz)
    curl -fSL -o "${TMP_TGZ}" "${TARBALL_URL}"
    TMP_DIR=$(mktemp -d /tmp/rita-XXXXXX)
    tar -xzf "${TMP_TGZ}" -C "${TMP_DIR}"

    echo "[*] Installing vendor files to ${OPT_RITA} and ${ETC_RITA}"
    mkdir -p "${OPT_RITA}" "${ETC_RITA}" "${ZEEK_LOGS}"
    cp -a "${TMP_DIR}/rita-v${RITA_VERSION}-installer/files/opt/." "${OPT_RITA}/"
    cp -a "${TMP_DIR}/rita-v${RITA_VERSION}-installer/files/etc/." "${ETC_RITA}/"
    rm -rf "${TMP_DIR}" "${TMP_TGZ}"

    # The vendor compose file carries a `build: .` key but ships no
    # Dockerfile; the image is prebuilt on ghcr. Drop the build key so
    # podman-compose pulls instead of building, and pre-pull for progress.
    sed -i '/^\s*build:\s*\./d' "${COMPOSE}"
    echo "[*] Pulling ghcr.io/activecm/rita:v${RITA_VERSION}"
    podman pull "ghcr.io/activecm/rita:v${RITA_VERSION}"

    # Debian's podman ships no unqualified-search registries, so short image
    # names (clickhouse/clickhouse-server) refuse to resolve. Allow docker.io.
    install -d -m 0755 /etc/containers/registries.conf.d
    printf 'unqualified-search-registries = ["docker.io"]\n' \
        > /etc/containers/registries.conf.d/ndr-rita.conf

    echo "[*] Bringing up the RITA stack under podman"
    compose up -d

    echo "[*] Installing the rita CLI wrapper -> ${BIN}"
    install -m 0755 /dev/null "${BIN}"
    cat > "${BIN}" <<'WRAPPER'
#!/usr/bin/env bash
# rita CLI wrapper: RITA v5 runs under podman (see /opt/ndr/rita.sh).
# Faithful translation of the vendor wrapper: every command is a one-off
# container on the stack network; `import <logs-dir> <dataset>` mounts the
# logs at /tmp/zeek_logs (the rita-import timer uses the equivalent flag
# form `import --database shaula --logs=/tmp/zeek_logs <logs-dir>`). The
# vendor compose stack (clickhouse + syslog-ng) is brought up first if not
# running; the rita service is not a daemon.
set -euo pipefail
COMPOSE=/opt/rita/docker-compose.yml
ZEEK_LOGS=/opt/zeek/logs
IMAGE=ghcr.io/activecm/rita:v5.1.2
NET=rita_rita-network

if [[ ${EUID} -ne 0 ]]; then exec sudo -E "$0" "$@"; fi

IS_IMPORT=false
LOGS=""
DATASET=""
POS_N=0
ARGS=()
while [[ $# -gt 0 ]]; do
    case "$1" in
        import)
            IS_IMPORT=true
            ;;
        --logs=*)
            LOGS="${1#*=}"
            ;;
        -l|--logs)
            LOGS="${2:-}"
            if [[ -z ${LOGS} ]]; then
                echo "rita wrapper: ${1} requires a value" >&2
                exit 2
            fi
            shift
            ;;
        --database=*)
            DATASET="${1#*=}"
            ;;
        -d|--database)
            DATASET="${2:-}"
            if [[ -z ${DATASET} ]]; then
                echo "rita wrapper: ${1} requires a value" >&2
                exit 2
            fi
            shift
            ;;
        -*)
            if [[ ${IS_IMPORT} = true ]]; then
                echo "rita wrapper: unrecognized flag for import: ${1}" >&2
                echo "rita wrapper: use the documented form: rita import <logs-dir> <dataset>" >&2
                exit 2
            fi
            ARGS+=("$1")
            ;;
        *)
            if [[ ${IS_IMPORT} = true ]]; then
                # Positional form: import <logs-dir> <dataset>. The first
                # bare positional is the host logs dir (it also wins over a
                # flag-provided --logs for the host-side mount), the second
                # is the dataset. Every consumed positional is shifted past
                # immediately, so the logs path can never leak into ARGS.
                POS_N=$((POS_N + 1))
                if [[ ${POS_N} -eq 1 ]]; then
                    LOGS="$1"
                elif [[ ${POS_N} -eq 2 && -z ${DATASET} ]]; then
                    DATASET="$1"
                else
                    echo "rita wrapper: unexpected positional argument for import: ${1}" >&2
                    echo "rita wrapper: use the documented form: rita import <logs-dir> <dataset>" >&2
                    exit 2
                fi
            else
                ARGS+=("$1")
            fi
            ;;
    esac
    shift
done

# Ensure the stack is up (idempotent; silent when already running)
if ! podman ps --format '{{.Names}}' | grep -q '^rita-clickhouse$'; then
    podman-compose -f "${COMPOSE}" up -d >/dev/null 2>&1 || true
fi

RUN_ARGS=(--rm --network "${NET}" -w / --env-file /opt/rita/.env
    -e DB_ADDRESS=rita-clickhouse:9000
    -v /opt/rita/.env:/.env
    -v /etc/rita/config.hjson:/config.hjson
    -v /etc/rita/http_extensions_list.csv:/etc/rita/http_extensions_list.csv
    -v /etc/rita/threat_intel_feeds:/etc/rita/threat_intel_feeds)

if [[ ${IS_IMPORT} = true ]]; then
    LOGS="${LOGS:-${ZEEK_LOGS}}"
    ABS=$(realpath "${LOGS}")
    [[ -e ${ABS} ]] || { echo "logs do not exist: ${ABS}" >&2; exit 1; }
    SRC="${ABS}"; [[ -f ${SRC} ]] && SRC=$(dirname "${SRC}")
    RUN_ARGS+=(-v "${SRC}:/tmp/zeek_logs")
    # The container command is rebuilt from scratch; neither the host logs
    # path nor the dataset positional is ever forwarded as a stray argument.
    ARGS=(import --database "${DATASET:-shaula}" --logs=/tmp/zeek_logs)
fi

podman run "${RUN_ARGS[@]}" "${IMAGE}" "${ARGS[@]}"
WRAPPER

    echo "[*] Verifying the stack"
    sleep 3
    podman ps --format '{{.Names}}: {{.Status}}' | grep rita || true
    rita version 2>/dev/null || rita --help 2>/dev/null | head -n 3 || \
        echo "[i] CLI responds through the API container; it may need a moment"

    echo "[+] RITA v${RITA_VERSION} installed under podman"
    echo "[i] Log import is wired by integrations/zeek-rita.sh"
}

remove() {
    echo "[*] Tearing down the RITA stack"
    if [[ -f ${COMPOSE} ]]; then
        compose down --volumes 2>/dev/null || true
    fi
    echo "[*] Removing RITA images"
    for img in $(podman images --format '{{.Repository}}:{{.Tag}}' 2>/dev/null \
        | grep -iE 'rita|syslog-ng|clickhouse' || true); do
        podman rmi "${img}" 2>/dev/null || true
    done

    echo "[*] Removing ${BIN}, ${OPT_RITA}, ${ETC_RITA}"
    rm -f "${BIN}"
    rm -rf "${OPT_RITA}" "${ETC_RITA}"
    rm -f /etc/containers/registries.conf.d/ndr-rita.conf
    systemctl disable --now rita-import.timer 2>/dev/null || true
    rm -f /etc/systemd/system/rita-import.{service,timer}
    systemctl daemon-reload 2>/dev/null || true
    # podman itself is left installed; remove it by hand if unwanted.

    echo "[+] rita removed"
}

status() {
    echo "[*] RITA containers:"
    podman ps -a --format '{{.Names}}: {{.Status}}' 2>/dev/null | grep rita || echo "none"
    echo "[*] rita CLI:"
    if [[ -x ${BIN} ]]; then
        rita --version 2>/dev/null || echo "present but not runnable"
    else
        echo "not installed"
    fi
    echo "[*] zeek log import timer:"
    systemctl is-enabled rita-import.timer 2>/dev/null || echo "not enabled (see integrations/zeek-rita.sh)"
}

case "${1:-}" in
    add)    add ;;
    remove) remove ;;
    status) status ;;
    *)      usage ;;
esac
