#!/bin/sh

set -e

help () {
    echo "Usage: ${0} [-hr] [-b environment]"
    echo 'Build a debian package from a python project.'
    echo ''
    echo 'Options:'
    echo ''
    echo ' -h --help:'
    echo '      Print this help and exit.'
    echo ''
    echo ' -r --release <tag>:'
    echo '      Build a package for release.'
    echo '      Do not append git versions to package name.'
    echo '      Instead, append .<tag>'
    echo ''
    echo ' -b --build <environment>:'
    echo '      Execute "./build.sh <environment>" to allow building other binary'
    echo '      artifacts (such as UI static files) before calling setup.py to create'
    echo '      a source distribution.'
    echo ''
    echo 'This script should be run in the git repository of the project, in the'
    echo 'same directory as 'setup.py'. The following files must be present:'
    echo ''
    echo ' - version.txt'
    echo '      Contains two entries separated by space:'
    echo '      1. The python package name given to setup(package=xxx).'
    echo '         If --release is not given an "extra version" derived from the'
    echo '         current tag/branch and commit hash is appended to the debian package'
    echo '         name. This makes two development versions always conflict each other.'
    echo '      2. The distribution version given to setup(version=vvv).'
    echo '         A "compatible version" is derived from the distribution version'
    echo '         by truncating it to only include major.minor segments. The'
    echo '         compatible version is used in debian/control Provides: package-vvv.'
    echo ''
    echo ' - debian_dependencies.txt'
    echo '      Contains a single line with debian packages and optionally versions as'
    echo '      should be specified in the Depends: package field.'
    echo ''
    echo ' - setup.py'
    echo '      Contains the distutils/setuptools setup() function.'
    echo ''
}

set -e

release=
build_env=

while [ -n "$1" ]; do
    if [ -z "$1" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
        help
        exit 1
    elif [ "$1" = "-r" ] || [ "$1" = "--release" ]; then
        release="$2"
        shift
    elif [ "$1" = "-b" ] || [ "$1" = "--build" ]; then
        build_env="$2"
        shift
    else
        echo "Unknown option: '$1'. Try '-h'"
        echo ""
        exit 2
    fi
    shift
done

project=
version=
extra_version=
git_commit=
git_tag=

project_version=$(cat version.txt)
for t in ${project_version}; do
    if [ -z "${project}" ]; then
        project="$t"
    elif [ -z "${version}" ]; then
        version="$t"
    fi
done

if [ -z "${project}" ] || [ -z "${version}" ]; then
    echo "Invalid project version in version.txt: '${project} ${version}'"
    exit 2
fi

compatible_version="$(echo ${version} | sed -e 's/\([^.]*[.][^.]*\).*$/\1/g')"

git_commit="$(git rev-parse --verify --short HEAD)"
git_commit="$(echo ${git_commit} | tr 'A-Z' 'a-z')"

if [ -z "${release}" ]; then
    git_tag="$(basename $(git describe --all --exact-match --abbrev=0 HEAD))"
    git_tag="$(echo ${git_tag} | tr 'A-Z' 'a-z')"
    extra_version="~dev+${git_tag}+${git_commit}"
else
    extra_version="+${release}+${git_commit}"
fi

export project version extra_version git_commit git_tag
if [ -n "${build_env}" ] && [ -e ./build.sh ]; then
    ./build.sh "${build_env}"
fi

venv="build-venv"
rm -rf "${project}".egg-info dist deb_dist "${venv}"

# add system site packages because we need to fulfill potentially
# unreleased requirements (e.g. apimas itself)
virtualenv --system-site-packages "${venv}"
. "${venv}"/bin/activate

pip_cache=".pip_cache"
mkdir -p "${pip_cache}" || true

"${venv}"/bin/pip install --upgrade pip
#"${venv}"/bin/pip install -r requirements.txt
"${venv}"/bin/pip install -r requirements_build.txt

debian_deps="$(cat debian_dependencies.txt)"
stdeb_cfg="mkdeb-stdeb.cfg"
echo "[DEFAULT]" > "${stdeb_cfg}"
echo "Package: python-${project}" >> "${stdeb_cfg}"
echo "Provides: python-${project}-${compatible_version}" >> "${stdeb_cfg}"
echo "Forced-Upstream-Version: ${version}${extra_version}" >> "${stdeb_cfg}"
echo "Depends: ${debian_deps}" >> "${stdeb_cfg}"

python setup.py --command-packages=stdeb.command \
                sdist_dsc \
                --extra-cfg-file="${stdeb_cfg}" \
                bdist_deb

deb_archive=$(find deb_dist -name '*.deb' | tail -1)
echo "${deb_archive}"
