#!/bin/sh
output=${1:-src/stub_revisited/__libc_start_main}
stack=${2:-${TEVWH_OUT}/stub_revisited/stack}

base_dir=$(
  find /usr/src/redhat/SOURCES -maxdepth 1 -type d -name 'glibc-*'
)

# If the file is not in the place I'm used to on my machine
# we fall back to the copy shipped with this document.
# Forcing my usage of SRPMs gains nothing.
[ -d "${base_dir}" ] || exit 0

${TEVWH_PATH_SED} -n -e 's/:/ /g' -e 's/^ *at *//p' < ${stack} \
| ( read original_filename line_number

  [ -n "${original_filename}" ] || exit 0
  filename="${base_dir}/${original_filename#../}"
  [ -e ${filename} ] || exit 0

  start=$( expr ${line_number} - 8 )
  end=$( expr ${line_number} + 4 )

  ( echo "# ${filename}"
    echo ""
    nl -ba -p ${filename} | ${TEVWH_PATH_SED} -n -e "${start},${end} p"
  ) > ${output}
)
