#!/bin/bash

set -e

die()
{
    printf "E: %s\n" "$*"
    exit 1
}

TARBALL="${1}"

[ ! -f "${TARBALL}" ] && die "Could not open ${TARBALL}"

TARBALL=$(readlink -e "${TARBALL}")

TARDIR=$(dirname "${TARBALL}")
GDB_VERSION=$(basename "${TARBALL}" | sed "s/^gdb-//; s/\.tar\.\(gz\|xz\|bz2\)\$//")
DEB_VERSION="${GDB_VERSION}"
DFSG_TAR="${TARDIR}/gdb_${DEB_VERSION}.orig.tar.xz"
DOC_TAR="${TARDIR}/gdb-doc_${GDB_VERSION}.orig.tar.xz"

tmpdir=$(mktemp -d)
trap 'rm -rf "${tmpdir}"' EXIT ERR INT

cd "${tmpdir}"
mkdir src
cd src
tar -xf "${TARBALL}"
cd ..

src=$(readlink -f "src/gdb-${GDB_VERSION}")
dest=$(readlink -f "gdb-${DEB_VERSION}")
destdoc=$(readlink -f "gdb-doc-${DEB_VERSION}")

[ ! -d "${src}" ] && die "Could not find source directory ${src}"

if [ -z "${dest}" ] || [ -e "${dest}" ]; then
  die "Could not create dest directory ${dest}"
fi

cp -a "${src}" "${dest}"
cp -a "${src}" "${destdoc}"

pushd "${dest}" > /dev/null

# All of the gdb manpages are GFDL'd now
find gdb -type f -name '*.[1-9]' -delete

# Almost all of the texinfo documentation is GFDL.  PSIM's is not, but
# we don't need that manual especially anyway.  Special care must be taken
# with observer.texi, which is necessary for the build process.  Remove
# all pregenerated info files, then replace all texinfo files with dummy
# versions.

find . -type f \( -name '*.info' -o -name '*.info-*' \) -delete
find . -type f -name '*.chm' -delete

find . -type f \( -name '*.texinfo' -o -name '*.texi' \) | \
    while read -r file; do
        if [ "$(basename "${file}")" = "observer.texi" ]; then
            sed -ne '/@c This/,/@c any later/p; /@deftype/p' "${src}/${file}" > "${file}"
            continue
        fi
        echo > "${file}"
    done

# for f in $(find . \( -name \*.texinfo -o -name \*.texi \)); do
#   if test $(basename $f) = observer.texi; then
#     sed -ne '/@c This/,/@c any later/p; /@deftype/p' "$src/$f" > $f
#     continue
#   fi

#   echo > "$f"
# done

popd > /dev/null

tar --auto-compress -cf "${DFSG_TAR}" "gdb-${DEB_VERSION}"

pushd "${destdoc}" > /dev/null
find . -type f -name '*.chm' -delete
popd > /dev/null

tar --auto-compress -cf "${DOC_TAR}" "gdb-doc-${DEB_VERSION}"
