#!/bin/bash

process_file() {
    local build_id=$(file --brief -e apptype -e ascii -e encoding -e cdf -e compress -e tar -- $1 | grep -oP 'BuildID\[sha1\]\s*=\s*\K[0-9a-f]+')

    build_id_prefix=${build_id:0:2}
    build_id_suffix=${build_id:2:38}

    mkdir -p debian/.debhelper/bpftrace/dbgsym-root/usr/lib/debug/.build-id/$(echo "$build_id" | cut -c1-2)
    objcopy --only-keep-debug --compress-debug-sections "$1" "debian/.debhelper/bpftrace/dbgsym-root/usr/lib/debug/.build-id/$build_id_prefix/$build_id_suffix.debug"
    chmod 0644 "debian/.debhelper/bpftrace/dbgsym-root/usr/lib/debug/.build-id/$build_id_prefix/$build_id_suffix.debug"
    objcopy --add-gnu-debuglink "debian/.debhelper/bpftrace/dbgsym-root/usr/lib/debug/.build-id/$build_id_prefix/$build_id_suffix.debug" "$1"
}

process_file $1
