#!/bin/bash

# Copyright (c) 2025 Cloudflare, Inc.
# Licensed under the Apache 2.0 license found in the LICENSE file or at:
#     https://opensource.org/licenses/Apache-2.0

die() {
    echo "[!] bpf_asm not found. Please put it in your \$PATH"
    echo "[!] you can typically find it in linux/tools/bpf/bpf_asm"
    exit 1
}

which bpf_asm > /dev/null || die

THISFILE=$0
CUTLINENUMBER=$(awk '/^# -- [A]UTOGENERATED/ {print FNR}' $THISFILE)
sed -i "$[CUTLINENUMBER]q" "$THISFILE"

cat <<EOF | bpf_asm -c >> $THISFILE

            ; load first byte to figure out short vs long packet
            ldb [0]
            and #0x80
            jeq #0x80, long_form, short_form

    long_form:
            ; in the load packet, check if the length is exactly 16 bytes
            ldb [5]
            jneq #16, bad_length
            ldx #6
            jmp parse_dcid

    bad_length:
            ret #-1

    short_form:
            ldx #1
            jmp parse_dcid

    parse_dcid:
           ; the cookie is big-endian two bytes in DCID
           ldh [x + 0]
           ret a
EOF
exit
# -- AUTOGENERATED FROM HERE --
{ 0x30,  0,  0, 0000000000 },
{ 0x54,  0,  0, 0x00000080 },
{ 0x15,  0,  5, 0x00000080 },
{ 0x30,  0,  0, 0x00000005 },
{ 0x15,  0,  2, 0x00000010 },
{ 0x01,  0,  0, 0x00000006 },
{ 0x05,  0,  0, 0x00000003 },
{ 0x06,  0,  0, 0xffffffff },
{ 0x01,  0,  0, 0x00000001 },
{ 0x05,  0,  0, 0000000000 },
{ 0x48,  0,  0, 0000000000 },
{ 0x16,  0,  0, 0000000000 },
