#!/bin/bash
# Sourced by root-owned entry points, before any network test or agent starts.
[[ $EUID -eq 0 ]] || exit 1
IFS=: read -r _ _ group_path < /proc/self/cgroup
attached=$(/usr/sbin/bpftool --json cgroup show "/sys/fs/cgroup$group_path")
out_id=$(/usr/sbin/bpftool --json prog show pinned /sys/fs/bpf/codex-guide-v1/egress | /usr/bin/jq -er 'if type == "array" then .[0].id else .id end')
in_id=$(/usr/sbin/bpftool --json prog show pinned /sys/fs/bpf/codex-guide-v1/ingress | /usr/bin/jq -er 'if type == "array" then .[0].id else .id end')
if ! /usr/bin/jq -e -s --argjson out "$out_id" --argjson inp "$in_id" '
    if length != 1 or (.[0] | type) != "array" then false
    else
        (.[0] | any(.[]; .attach_type == "egress" and .id == $out)) and
        (.[0] | any(.[]; .attach_type == "ingress" and .id == $inp))
    end
' <<< "$attached" >/dev/null; then
    echo 'Expected network filters are not attached; no command was started' >&2
    exit 1
fi
