#!/bin/sh
# This script collects all relevant binaries (executable + shared libraries) as determined
# from the given core file.
# Usage: ./appoptics-packcore.sh <COREFILE>

if [ -z "$1" ]; then
    echo "Please provide the path to the core file."
    exit 1
fi
if [ ! -f "$1" ]; then
    echo "Core file $1 not found."
    exit 1
fi
if [ -z "$(file $1 | grep "core file")" ]; then
    echo "File $1 does not appear to be a core file."
    exit 1
fi

CORE=$1

if [ -z "$(which xz 2>/dev/null)" ]; then
    echo "Could not find 'xz' command, please install package xz-utils."
    exit 1
fi

echo -n "Extracting executable path from core file... "

# various attempts to determine the executable path from core file
EXE=$(file $CORE | grep "execfn: " | sed "s/.*execfn: '\([^']*\)'.*/\1/")
if [ -z "$EXE" ]; then
    EXE=$(file $CORE | grep "from " | sed "s/.*from '\([^']*\)'.*/\1/" | awk '{print $1}' | sed "s/://g")
fi
if [ -z "$EXE" ]; then
    EXE=$(strings $CORE | grep ^/ | tail -1)
fi
if [ -z "$EXE" ]; then
    echo "could not determine the executable path from core file."
    exit 1
fi

# get full path to executable
EXE=$(which $EXE)

echo $EXE
echo -n "Determine shared object dependencies... "

# determine shared object dependencies and record their path
LIBS=$(
    ldd $EXE |
    awk '
    /=> \// {print $3}
        ! /=>/ {print $1}
    '
    )

echo "done"
echo "Archive all relevant binaries and core file..."

# archive all relevant binaries
ARCHIVE=$(basename $CORE)-all.tar.xz
cat <<EOF | tar -vcah -T- -f $ARCHIVE
$EXE
$LIBS
$CORE
EOF

echo
echo "Done: $ARCHIVE"
