#!/bin/bash

copydebug() {
	src="$1"
	destpath="$2"
	fo=$(file "$src") || { echo "File '$src' not found" >&2 ; return 1 ; }
##  [1]="d6" [2]="5c6fd11bc9703f3bca69b41df1b8e5487ce10e" [3]="with%debug_info,%" [4]="not%stripped" [5]="not%" [6]="stripped")
	[[ "${fo// /%}" =~ .*BuildID[[]sha[0-9]+[]]=([a-fA-F0-9][a-fA-F0-9])([a-fA-F0-9]+),%?(for%GNU/Linux%[0-9.]+,%)?(with%debug_info,%)?((not%)?(stripped)).*  ]] \
		|| { echo "Unable to parse build id from '$src'" ; return 1 ; }
	[[ "${BASH_REMATCH[4]}" == "with%debug_info,%" ]] && return 0
	sdir="/usr/lib/debug/.build-id/${BASH_REMATCH[1]}"
	sfile="$sdir/${BASH_REMATCH[2]}.debug"
	[[ ! -e "$sfile" ]] && { echo "'$src' was stripped but no debug info was found" >&2 ; return 1 ; }
	cp --parents -R "$sfile" "${destpath}/"
	sbase=$(basename "$src")
	sfiles=$(find -L /usr/lib/debug/ -name "$sbase*")
	for f in $sfiles ; do
		cp --parents -R "$f" "${destpath}/"
	done
}

date=$(date --utc -Is | tr ':' '-')
date=${date%%+*}
destdir=asterisk-info-${date}

[ -z "$1" ] && {
	echo -e "Usage: '$0 <temp_dir>'\n  '<temp_dir>/asterisk-info-<timestamp>.tar.gz' will be created." >&2
	exit 1
}

tempdir="$1"

[ "$tempdir" == "-h" ] || [ "$tempdir" == "--help" ] && {
	echo -e "Usage: '$0 <temp_dir>'\n  '<temp_dir>/asterisk-info-<timestamp>.tar.gz' will be created." >&2
	exit 1
}

[ ! -d "${tempdir}" ] && {
	echo "Temporary directory '$tempdir' doesn't exist.  Please create it." >&2
	exit 1
}

destpath=${tempdir}/${destdir}
[ -d "${destpath}" ] && rm -rf "${destpath}"
echo "Creating '${destpath}'"
mkdir "${destpath}" || {
	echo "ERROR: Unable to create '${destpath}'" >&2
	exit 1
}

copypath() {
	for f in "$@" ; do
		[ ! -e "${f}" ] && continue
		f=$(realpath -s "${f}")
		echo "Copying '${f}' -> '${destpath}'"
		cp --parents -R "${f}" "${destpath}/" || {
			echo "ERROR: Unable to copy '${f}' -> '${destpath}/'" >&2
			exit 1
		}
	done
}

copypath /usr/{,local/}{,s}bin/asterisk
copypath /usr/{,local/}lib{,64}/asterisk
copypath /usr/{,local/}lib{,64}/libasterisk*
copypath /etc/os-release

files=$(find "${destpath}" -type f -executable)
for f in $files ; do
	copydebug "$f" "$destpath"
done

cd "${tempdir}" || exit 1

echo "Creating ${destpath}.tar.gz"
tar -czf "${destdir}.tar.gz" "${destdir}"
echo "Created ${destpath}.tar.gz"
rm -rf ${destpath}
