#!/bin/bash

# make a tarbal of build artifacts needed for perf ingest

set -euxo pipefail

rm -r /tmp/perf-symbols || true
mkdir -p /tmp/perf-symbols
pushd /tmp/perf-symbols

mkdir -p input
out=`pwd`/output
mkdir -p $out
mkdir -p $out/lib
mkdir -p $out/usr/lib

pushd input

# get kernel build
aws s3 cp s3://zoox-web/austin/linux-4.19.72-3.tgz .
tar xf linux-4.19.72-3.tgz # note: has own top level directory
pushd linux-4.19.72-3 # from above tar

function pushd_deb() {
    d="${1%.*}";
    mkdir -p "$d"
    pushd "$d"
    dpkg-deb -x "../$1" .
}

function pushd_apt() {
    mkdir -p "$1"
    pushd "$1"
    apt-get download "$1"
    dpkg-deb -x *.deb .
}


# regular modules
pushd_deb linux-modules-4.19.72-3-zoox_4.19.72-3_amd64.deb
mkdir -p $out/lib/
cp lib/modules $out/lib/ -R
popd

# debug modules
pushd_deb linux-image-4.19.72-3-zoox-dbgsym_4.19.72-3_amd64.deb
mkdir -p $out/usr/lib/
cp usr/lib/debug $out/usr/lib/ -R
popd
popd # linux


# user libs
pushd_apt libc6-dbg
mkdir -p $out/usr/lib/debug/lib/
cp usr/lib/debug/lib/x86_64-linux-gnu $out/usr/lib/debug/lib/ -R
popd

pushd_apt libc6
mkdir -p $out/lib/
cp lib/x86_64-linux-gnu $out/lib/ -R
popd

pushd_apt libstdc++6
mkdir -p $out/usr/lib/x86_64-linux-gnu/
cp usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28 $out/usr/lib/x86_64-linux-gnu/
popd

# TODO usr/lib/x86_64-linux-gnu/debug/libstdc++.so.6.0.28
# one of these? apt search libstdc++6 | grep amd64 | grep dbg

# TODO libpython2.7-dbg:amd64 ? (will be handled by ZRTE)
# TODO libpython3.4-dbg:amd64 (same)

popd # input


# tar results
pushd output
ln -s usr/lib/debug/boot/vmlinux* vmlinux

name="debug_symbols_4.19.72-3-zoox_`date '+%Y-%m-%d'`.tar.gz"
tar cfa ../$name .

popd # output

fullpath="/tmp/perf-symbols/$name"

set +x
echo "Symbol archive created at $fullpath"
echo "To upload:"
echo "    aws s3 cp $fullpath s3://zoox-web/perf/debug-symbols/"
