#!/bin/sh

set -e
#set -x

if [ "${1}" = "-u" ] && [ -n "${2}" ] ; then
	ORIG_URL="${2}"
	shift
	shift
fi

if [ -z "${1}" ] ; then
	echo "This tool creates a template Debian package out of a PyPi package name."
	echo "Once this script has run, make sure it did what you expected, then use"
	echo "the newly created source package as a template. Make sure you correct"
	echo "the debian/copyright file before publishing any package."
	echo "Usage: ${0} package-name"
	exit 1
fi

PKG_NAME=${1}
RUN_DIR=$(pwd)
# Calculate the package name based on the command line argument
LOWER_PKG_NAME=`echo ${PKG_NAME} | awk '{print tolower($0)}'`
LOWER_PKG_NAME=`echo ${LOWER_PKG_NAME} | sed 's/_/-/g'`
if echo ${LOWER_PKG_NAME} | grep -q '^python-' ; then
	DEB_PKG_NAME=${LOWER_PKG_NAME}
else
	DEB_PKG_NAME=python-${LOWER_PKG_NAME}
fi
echo "===> Package name will be ${DEB_PKG_NAME}"

if ! [ -e ${PKG_NAME}.json ] ; then
	wget https://pypi.org/pypi/${PKG_NAME}/json -O ${PKG_NAME}.json
fi
PY3_PKG_NAME=python3-$(echo ${DEB_PKG_NAME} | sed 's/python-//g')

# Get the info from .json using jq
VERSION_STRING=$(cat ${PKG_NAME}.json | jq --raw-output '. | .info.version')
    SHORT_DESC=$(cat ${PKG_NAME}.json | jq --raw-output '. | .info.summary')
 UP_MAINT_NAME=$(cat ${PKG_NAME}.json | jq --raw-output '. | .info.author')
  AUTHOR_EMAIL=$(cat ${PKG_NAME}.json | jq --raw-output '. | .info.author_email')
      HOMEPAGE=$(cat ${PKG_NAME}.json | jq --raw-output '. | .info.home_page')
  FIRST_LETTER=$(echo ${PKG_NAME} | awk '{print substr($0,1,1)}')

if [ -e ${DEB_PKG_NAME}_${VERSION_STRING}.orig.tar.xz ] ; then
	ORIG=${DEB_PKG_NAME}_${VERSION_STRING}.orig.tar.xz
else
	ORIG=${DEB_PKG_NAME}_${VERSION_STRING}.orig.tar.gz
fi

if [ ! -e ${ORIG} ] ; then
	echo "===> Downloading ${ORIG} file"
	if [ -z "${ORIG_URL}" ] ; then
		if [ $(cat ${PKG_NAME}.json | jq --raw-output '. | .urls[0].packagetype') = "sdist" ] ; then
			ORIG_URL=$(cat ${PKG_NAME}.json | jq  --raw-output '. | .urls[0].url')
		else
			if [ $(cat ${PKG_NAME}.json | jq --raw-output '. | .urls[1].packagetype') = "sdist" ] ; then
				ORIG_URL=$(cat ${PKG_NAME}.json | jq  --raw-output '. | .urls[1].url')
			else
				echo "First and 2nd URL aren't sdist, please manually download..."
				exit 1
			fi
		fi
	fi
	wget -nv "${ORIG_URL}" -O ${ORIG}
fi

echo "===> Extracting ${ORIG}"
if ! [ -e ${DEB_PKG_NAME}-${VERSION_STRING} ] ; then
	tar -xf ${ORIG}
	if ! [ ${PKG_NAME}-${VERSION_STRING} = ${DEB_PKG_NAME}-${VERSION_STRING} ] ; then
		# The sed is in case there's a package called package_name with underscore, in which
		# case we want to replace that by dash
		mv $(echo ${PKG_NAME} | sed 's#_#*#g' | sed 's#-#*#g')-${VERSION_STRING} ${DEB_PKG_NAME}-${VERSION_STRING}
	fi
fi

if [ -z "${HOMEPAGE}" ] || [ "${HOMEPAGE}" = "null" ] ; then
	echo -n "Could not find homepage URL. Please enter it: "
	read HOMEPAGE
fi

echo "===> Package info:
Upstream version: ${VERSION_STRING}
Author: ${UP_MAINT_NAME}
Homepage: ${HOMEPAGE}"

echo "===> Cloning package:"
if ! [ -d ${DEB_PKG_NAME} ] ; then
	git clone ${HOMEPAGE} ${DEB_PKG_NAME}
fi

echo "===> Getting info"
echo "For which team should this be packaged?"
TEAM_NAME=$(pkgos-choose "For which team should this be packaged?" "OpenStack team" "Python team" "Home Assistant team")
case ${TEAM_NAME} in
"OpenStack team")
	TEAM=openstack
	MAINTAINER_FIELD="Debian OpenStack <team+openstack@tracker.debian.org>"
	VCS_URL_START=https://salsa.debian.org/openstack-team/libs
;;
"Python team")
	TEAM=python
	MAINTAINER_FIELD="Debian Python Team <team+python@tracker.debian.org>"
	VCS_URL_START=https://salsa.debian.org/python-team/packages
;;
"Home Assistant team")
	TEAM=homeassistant
	MAINTAINER_FIELD="Home Assistant Team <team+homeassistant@tracker.debian.org>"
	VCS_URL_START=https://salsa.debian.org/homeassistant-team/deps
;;
*)
	echo "Try again, bye bye..."
	exit 1
;;
esac

echo "===> Checking for license:"

# Find a license file at the root of the cloned package.
LICENSE_FILE=""
for CAND in $(find ${DEB_PKG_NAME} -maxdepth 1 \( -iname 'LICENSE*' -o -iname 'LICENCE*' -o -iname 'COPYING*' \) 2>/dev/null | sort) ; do
	LICENSE_FILE=${CAND}
	break
done

detect_file_licenses () {
	# $1 = license file path. Echos the detected license titles.
	if grep -qiE "Version 2\.0, January 2004|Apache License,? Version 2\.0|apache\.org/licenses/LICENSE-2\.0|Apache Software License 2\.0" ${1} ; then
		echo Apache-2.0
	fi
	if grep -qi "Permission is hereby granted, free of charge" ${1} ; then
		echo Expat
	fi
	if grep -qi "Redistribution and use in source and binary forms" ${1} ; then
		if grep -qi "Neither the name" ${1} ; then
			echo BSD-3-clause
		else
			echo BSD-2-clause
		fi
	fi
	if grep -qi "GNU LESSER GENERAL PUBLIC LICENSE" ${1} ; then
		if grep -qiE "version 3|Version 3" ${1} ; then
			echo LGPL-3+
		else
			echo LGPL-2.1
		fi
	elif grep -qi "GNU GENERAL PUBLIC LICENSE" ${1} ; then
		if grep -qiE "version 3|Version 3" ${1} ; then
			echo GPL-3+
		else
			echo GPL-2+
		fi
	fi
	return 0
}

detect_pypi_licenses () {
	# Echos the detected license titles from the PyPI metadata.
	if [ ! -e ${PKG_NAME}.json ] ; then
		return 0
	fi
	INFO_EXPR=$(jq --raw-output '.info.license_expression // ""' ${PKG_NAME}.json 2>/dev/null)
	case ${INFO_EXPR} in
	Apache-2.0*) echo Apache-2.0 ;;
	MIT*|MIT-0) echo Expat ;;
	BSD-2-Clause*) echo BSD-2-clause ;;
	BSD-3-Clause*) echo BSD-3-clause ;;
	GPL-2*) echo GPL-2+ ;;
	GPL-3*) echo GPL-3+ ;;
	LGPL-2*) echo LGPL-2.1 ;;
	LGPL-3*) echo LGPL-3+ ;;
	esac
	INFO_LICENSE=$(jq --raw-output '.info.license // ""' ${PKG_NAME}.json 2>/dev/null)
	case ${INFO_LICENSE} in
	Apache*) echo Apache-2.0 ;;
	MIT) echo Expat ;;
	BSD*) echo BSD-2-clause ;;
	*GPLv3*|*GPL-3*|*"version 3"*) echo GPL-3+ ;;
	*GPLv2*|*GPL-2*) echo GPL-2+ ;;
	*LGPL*3*) echo LGPL-3+ ;;
	*LGPL*) echo LGPL-2.1 ;;
	esac
	jq --raw-output '.info.classifiers[]? | select(startswith("License :: OSI Approved")) | sub("^License :: OSI Approved :: "; "")' ${PKG_NAME}.json 2>/dev/null | while read -r CLASSIFIER ; do
		case ${CLASSIFIER} in
		"Apache Software License") echo Apache-2.0 ;;
		"MIT License") echo Expat ;;
		"BSD License") echo BSD-2-clause ;;
		*LGPL*3*) echo LGPL-3+ ;;
		*LGPL*) echo LGPL-2.1 ;;
		*GPL*3*) echo GPL-3+ ;;
		*GPL*) echo GPL-2+ ;;
		esac
	done
	return 0
}

DETECTED=""
DETECT_SOURCE="PyPI metadata"
if [ -n "${LICENSE_FILE}" ] ; then
	DETECTED=$(detect_file_licenses ${LICENSE_FILE})
	DETECT_SOURCE="${LICENSE_FILE}"
fi
if [ -z "${DETECTED}" ] ; then
	DETECTED=$(detect_pypi_licenses)
fi
DETECTED=$(echo ${DETECTED} | tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/^ *//;s/ *$//')
NB_DETECT=$(echo ${DETECTED} | wc -w)
if [ "${NB_DETECT}" = "1" ] && [ -n "${DETECTED}" ] ; then
	LICENSE_TITLE=${DETECTED}
	echo "===> Detected license: ${LICENSE_TITLE} (from ${DETECT_SOURCE})"
else
	if [ -n "${DETECTED}" ] ; then
		echo "===> Multiple or unclear licenses detected (${DETECTED}), please choose:"
	else
		echo "===> Could not detect any license, please choose:"
	fi
	LICENSE_TITLE=$(pkgos-choose "What is the license of this package?" "Apache-2.0" "BSD-2-clause" "BSD-3-clause" "Expat" "GPL-2+" "GPL-3+" "LGPL-2.1" "LGPL-3+" "Other")
	case ${LICENSE_TITLE} in
	Other) LICENSE_TITLE=TODO ;;
	esac
fi

case ${LICENSE_TITLE} in
Apache-2.0)
	LICENSE_TEXT=" Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 .
    http://www.apache.org/licenses/LICENSE-2.0
 .
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an \"AS IS\" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 .
 On Debian-based systems the full text of the Apache version 2.0 license
 can be found in /usr/share/common-licenses/Apache-2.0.
"
;;
BSD-2-clause)
	LICENSE_TEXT=""
;;
BSD-3-clause)
	LICENSE_TEXT=" Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 3. Neither the name of the copyright holder nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.
 .
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"
;;
Expat)
	LICENSE_TEXT=" Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the \"Software\"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 .
 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.
 .
 THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
"
;;
GPL-2+)
	LICENSE_TEXT=" This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.
 .
 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 .
 You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
 St, Fifth Floor, Boston, MA 02110-1301 USA
 .
 On Debian systems, the complete text of the GNU General Public License v2
 (GPL) can be found in /usr/share/common-licenses/GPL-2.
"
;;
GPL-3+)
	LICENSE_TEXT=" This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3 of the License, or (at your option) any later
 version.
 .
 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 .
 You should have received a copy of the GNU General Public License along with
 this program; if not, see <http://www.gnu.org/licenses/>.
 .
 On Debian systems, the complete text of the GNU General Public License v3
 (GPL) can be found in /usr/share/common-licenses/GPL-3.
"
;;
LGPL-2.1)
	LICENSE_TEXT=" This library is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free
 Software Foundation; either version 2.1 of the License, or (at your option) any
 later version.
 .
 This library is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 details.
 .
 You should have received a copy of the GNU Lesser General Public License along
 with this library; if not, write to the Free Software Foundation, Inc., 51
 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 .
 On Debian systems, the complete text of the GNU Lesser General Public License
 (LGPL) may be found in /usr/share/common-licenses/LGPL-2.1.
"
;;
LGPL-3+)
	LICENSE_TEXT=" This library is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free
 Software Foundation; either version 3 of the License, or (at your option) any
 later version.
 .
 This library is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 details.
 .
 You should have received a copy of the GNU Lesser General Public License along
 with this library; if not, see <http://www.gnu.org/licenses/>.
 .
 On Debian systems, the complete text of the GNU Lesser General Public License
 (LGPL) may be found in /usr/share/common-licenses/LGPL-3.
"
;;
TODO)
	LICENSE_TEXT=" TODO"
;;
*)
	echo "Unknown entry: bye bye..."
	exit 1
;;
esac

echo "===> Creating debian folder for ${DEB_PKG_NAME}"
if [ ! -d ${DEB_PKG_NAME}-${VERSION_STRING}/debian/source ] ; then
	mkdir -p ${DEB_PKG_NAME}-${VERSION_STRING}/debian/source
fi
cd ${DEB_PKG_NAME}-${VERSION_STRING}

echo "===> Searching for sphinx doc folder"
if [ -e doc ] ; then
	DOC_FOLDER=doc
elif [ -e docs ] ; then
	DOC_FOLDER=docs
fi
if [ -n "${DOC_FOLDER}" ] ; then
	CONFPY_FILE=`find ${DOC_FOLDER} -name 'conf.py'`
	if [ -r "${CONFPY_FILE}" ] ; then
		DOC_FOLDER=`dirname ${CONFPY_FILE}`
		SPHINX_BUILD_DEP=", python3-sphinx"
		RULES_WITH=",sphinxdoc"
		SUGGEST_DOC="
Suggests: ${DEB_PKG_NAME}-doc"
	else
		DOC_FOLDER=
		SPHINX_BUILD_DEP=""
		RULES_WITH=""
		SUGGEST_DOC=""
	fi
fi

echo "===> Checking for PBR and fixing accordingly"
# If the package uses PBR, then we need openstack-pkg-tools
if grep -q "setup_requires=\['pbr'\]" ${DEB_PKG_NAME}-${VERSION_STRING}/setup.py ; then
	OSTACK_PKG_T_CTRL=", openstack-pkg-tools"
	# We need a mandatory include...
	# ... and the export OSLO_PACKAGE_VERSION=$(VERSION)
	OSTACK_PKG_T_RULES="include /usr/share/openstack-pkg-tools/pkgos.make
export OSLO_PACKAGE_VERSION=\$(VERSION)"
else
	# Otherwise, we just include it non-mandatorily, so that
	# we can use ./debian/rules gen-orig-xz
	OSTACK_PKG_T_CTRL=""
	OSTACK_PKG_T_RULES="include /usr/share/openstack-pkg-tools/pkgos.make"
fi

echo "===> Creating debian/control"
echo "Source: ${DEB_PKG_NAME}
Section: python
Priority: optional
Maintainer: ${MAINTAINER_FIELD}
Uploaders:
 Thomas Goirand <zigo@debian.org>,
Build-Depends:
 debhelper-compat (= 11),
 dh-python,
 pybuild-plugin-pyproject,
 openstack-pkg-tools,
 python3-setuptools,
 python3-all${SPHINX_BUILD_DEP}${OSTACK_PKG_T_CTRL}
Build-Depends-Indep:
 python3-pytest,
Standards-Version: 4.6.1
Vcs-Browser: ${VCS_URL_START}/${DEB_PKG_NAME}
Vcs-Git: ${VCS_URL_START}/${DEB_PKG_NAME}.git
Homepage: ${HOMEPAGE}

Package: ${PY3_PKG_NAME}
Architecture: all
Depends: \${python3:Depends}, \${misc:Depends}${SUGGEST_DOC}
Description: ${SHORT_DESC}
 This package provides 
 .
 This package
" >debian/control

if [ -n "${DOC_FOLDER}" ] ; then
	echo "Package: python-"$(echo ${LOWER_PKG_NAME} | sed s/python-//)"-doc
Section: doc
Architecture: all
Depends: \${misc:Depends}, \${sphinxdoc:Depends}
Description: ${SHORT_DESC} - doc
 - REPLACE ME -
 .
 This package contains the documentation.
" >>debian/control

	echo "Document: ${DEB_PKG_NAME}-doc
Title: ${PKG_NAME} Documentation
Author: N/A
Abstract: Sphinx documentation for ${PKG_NAME}
Section: Programming/Python

Format: HTML
Index: /usr/share/doc/python-${LOWER_PKG_NAME}-doc/html/index.html
Files: /usr/share/doc/python-${LOWER_PKG_NAME}-doc/html/*" >debian/python-${LOWER_PKG_NAME}-doc.doc-base
fi

EDITOR=touch dch --create --package ${DEB_PKG_NAME} --distribution unstable --urgency medium -v ${VERSION_STRING}-1
rm +1

echo "===> Creating debian/copyright"
if [ -n "${AUTHOR_EMAIL}" ] ; then
	UP_MAINT_AND_EMAIL="${UP_MAINT_NAME} <${AUTHOR_EMAIL}>"
else
	UP_MAINT_AND_EMAIL=${UP_MAINT_NAME}
fi
echo "Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: ${PKG_NAME}
Source: ${HOMEPAGE}

Files: *
Copyright: (c) 2024, ${UP_MAINT_AND_EMAIL}
License: ${LICENSE_TITLE}

Files: debian/*
Copyright: (c) 2024, Thomas Goirand <zigo@debian.org>
License: ${LICENSE_TITLE}

License: ${LICENSE_TITLE}
${LICENSE_TEXT}
" >debian/copyright

echo "===> Creating debian/rules"
if [ -n "${DOC_FOLDER}" ] ; then
	SPHINX_BUILD_RULES="override_dh_sphinxdoc:
ifeq (,\$(findstring nodoc, \$(DEB_BUILD_OPTIONS)))
	PYTHONPATH=. python3 -m sphinx -b html ${DOC_FOLDER} debian/python-"$(echo ${LOWER_PKG_NAME} | sed s/python-//)"-doc/usr/share/doc/python-"$(echo ${LOWER_PKG_NAME} | sed s/python-//)"-doc/html
	dh_sphinxdoc
endif
"
else
	SPHINX_BUILD_RULES=""
fi

if [ -e .testr.conf ] || [ -e .stestr.conf ] ; then
	UNIT_TEST_RULES="override_dh_auto_test:
ifeq (,\$(findstring nocheck, \$(DEB_BUILD_OPTIONS)))
	pkgos-dh_auto_test --no-py2
endif
"
else
	UNIT_TEST_RULES="
ifeq (,\$(findstring nocheck, \$(DEB_BUILD_OPTIONS)))
	set -e ; for pyvers in \$(PYTHON3S); do \\
		python\$\$pyvers setup.py test ; \\
	done
endif
"
fi

echo "#!/usr/bin/make -f

UPSTREAM_GIT := ${HOMEPAGE}.git
${OSTACK_PKG_T_RULES}

%:
	dh \$@ --buildsystem=pybuild --with python3${RULES_WITH}

${SPHINX_BUILD_RULES}
" >debian/rules
chmod +x debian/rules

#echo "/usr" >debian/python3-${LOWER_PKG_NAME}.install
echo "===> Creating debian/watch and debian/source"
if echo ${HOMEPAGE} | grep -q github.com ; then
	echo "version=4
opts=\"dversionmangle=auto,mode=git,uversionmangle=s/\.0rc/~rc/;s/\.0b1/~b1/;s/\.0b2/~b2/;s/\.0b3/~b3/\" \
${HOMEPAGE} refs/tags/(\d[brc\d\.]+)
" >debian/watch
else
	echo "version=3
opts=uversionmangle=s/(rc|a|b|c)/~\$1/ \\
https://pypi.debian.net/${PKG_NAME}/${PKG_NAME}-(.+)\.(?:zip|tgz|tbz|txz|(?:tar\.(?:gz|bz2|xz)))
" >debian/watch
fi

echo "3.0 (quilt)" >debian/source/format
echo 'extend-diff-ignore = "^[^/]*[.]egg-info/"' >debian/source/options

echo "===> Adding pybuild-autopkgtest in debian/tests"
mkdir -p debian/tests
echo "Test-Command: pybuild-autopkgtest
Depends: @, @builddeps@, pybuild-plugin-autopkgtest
Restrictions: allow-stderr, skippable,
Features: test-name=pybuild-autopkgtest
" >debian/tests/control

echo "===> Attempting to configure the Debian repo"
cd ../${DEB_PKG_NAME}
if git show v${VERSION_STRING} >/dev/null 2>/dev/null; then
	git tag ${VERSION_STRING} v${VERSION_STRING}
fi
if ! git show ${VERSION_STRING} >/dev/null 2>/dev/null ; then
	echo "Cannot find upstream tag: exiting."
	exit 1
fi

git reset --hard ${VERSION_STRING}
GIT_CUR_BRANCH=$(git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
git checkout -b debian/unstable
git branch -D ${GIT_CUR_BRANCH}
cp -axuf ../${DEB_PKG_NAME}-${VERSION_STRING}/debian .
git add debian
if which wrap-and-sort >/dev/null 2>&1 ; then
	wrap-and-sort -bastk
fi

echo "===> Regenerating orig tarball"
if [ -e /usr/share/openstack-pkg-tools/pkgos.make ] ; then
	rm -f ../*.orig.tar.*
	./debian/rules gen-orig-xz
else
	echo "===> Install openstack-pkg-tools to be able to run 'debian/rules gen-orig-xz'."
fi

echo "===> Writing ITP text to ${RUN_DIR}/itp.txt"
cat >${RUN_DIR}/itp.txt <<ITPEOF
* Package name    : ${DEB_PKG_NAME}
  Version         : ${VERSION_STRING}
  Upstream Author : ${UP_MAINT_AND_EMAIL}
* URL             : ${HOMEPAGE}
* License         : ${LICENSE_TITLE}
  Programming Lang: Python
  Description     : ${SHORT_DESC}
ITPEOF

echo "===> Launching reportbug"
if which pkgos-reportbug >/dev/null 2>&1 && [ -z "${PKGOS_DEBPIPY_NO_REPORTBUG}" ] ; then
	pkgos-reportbug ${RUN_DIR}/itp.txt
else
	echo "===> Not launching reportbug (not installed, or PKGOS_DEBPIPY_NO_REPORTBUG is set)."
	echo "===> Please run the following command, then review and send the ITP:"
	echo "pkgos-reportbug ${RUN_DIR}/itp.txt"
fi
