#!/usr/bin/env bash

# This script extracts a package from a tool and prints it to stdout,
# excluding the 1; line that should mark the end of the package.
#
# All package lines are printed as-is (i.e. comments are included).
#
# Exits 0 on success, else 1 on warnings and errors.

die() {
   echo "$1" >&2
   exit 1
}

pkg="$1"
tool="$2"
if [ -z "$pkg" ] || [ -z "$tool" ]; then
   die "Usage: $0 PACKAGE TOOL"
fi

# Package names cannot have - characters; they should be _ instead.
# This allows caller to specify "tool-name tool-name" to extract
# package tool_name from tool-name.
perl_pkg=${pkg//-/_}

pkg_start_line=$(grep --line-number "^# Package: $perl_pkg$" $tool | cut -d':' -f1)
if [ -z "$pkg_start_line" ]; then
   pkg_start_line=$(grep --line-number "^package $perl_pkg;" $tool | cut -d':' -f1)
   if [ -z "$pkg_start_line" ]; then
      die "Cannot find package $perl_pkg in $tool"
   fi
fi

# The package should end with a line that starts with 1;.
tail -n +$pkg_start_line $tool | awk '/^1;/ { print; exit; } { print }'

exit $?
