#!/bin/bash -e
#                                                         -*-shell-script-*-
# Placed into the public domain by John Morris, 2014
#
# Configure source package dependencies

# List of supported kernel arches for kthreads
KTHREAD_ARCHES="i386 amd64"
if test -x /usr/bin/lsb_release; then
    DISTRO_ID=$(lsb_release -is)  # Debian or Ubuntu
    DISTRO_RELEASE=$(lsb_release -rs)   # 8.1, 14.04, etc.
    DISTRO_CODENAME=$(lsb_release -cs) # wheezy | jessie | stretch | buster
fi

# Work out of the debian/ directory
cd "$(dirname $0)"

# Put command into a file so that later automatic invocations can
# re-run
echo $0 $* > configure.cmdline

rules_enable_threads() {
    # enable thread flavors in debian/rules; e.g.
    #    THREADS_POSIX = --with-posix
    FLAVOR=$1
    FLAVOR_VAR=THREADS_$(echo $FLAVOR | tr 'a-z-' 'A-Z_')
    sed -i rules \
	-e "s/^${FLAVOR_VAR}[^_].*/${FLAVOR_VAR} = --with-${FLAVOR}/"
    echo "debian/rules:  enabled ${FLAVOR} threads" >&2
}

guess_arch_from_kver() {
    # utility to make a guess at the kernel header arch from the
    # kernel version; this works for Debian kernels, and 'any' is
    # correct for the RTAI kernel packages in the Machinekit Debian
    # archive
    KVER=$1
    case $KVER in
	*-?86 | *-?86-pae) echo i386 ;;
	*-amd64) echo amd64 ;;
	*) echo any ;;  # For non-Debian kernel package naming
    esac
}

do_posix() {
    cat control.d/control.posix.hdr control.d/control.$DISTRO_CODENAME.in control.d/control.posix.ftr >> control
    echo "debian/control:  added POSIX threads package" >&2
    rules_enable_threads posix
    HAVE_FLAVOR=true
}

do_rt-preempt() {
    cat control.d/control.rt-preempt.hdr control.d/control.$DISTRO_CODENAME.in control.d/control.rt-preempt.ftr >> control
    echo "debian/control:  added RT_PREEMPT threads package" >&2
    rules_enable_threads rt-preempt
    HAVE_FLAVOR=true
}

do_xenomai() {
    cat control.d/control.xenomai.hdr control.d/control.$DISTRO_CODENAME.in control.d/control.xenomai.ftr >> control
#    sed -i "s|yapps2-runtime|yapps2-runtime, xenomai-runtime|" control
    echo "debian/control:  added xenomai threads package for Jessie" >&2
    # Be sure the -dev files only appear once
    BUILD_DEPS="${BUILD_DEPS/libxenomai-dev, /}libxenomai-dev, "
    echo "debian/control:  added Xenomai (userland) threads package" \
	"with Build-Depends:" >&2
    echo "    libxenomai-dev" >&2
    rules_enable_threads xenomai
    HAVE_FLAVOR=true
}

## Set version for packages by altering changelog
## Write new version info then prepend existing one, for use in changes file
## Allows command line builds and builds outside of Travis environment to set meaningful version numbers

do_changelog() {
    DISTRO_UC="$(echo $DISTRO_CODENAME | sed 's/^[[:space:]]*//g' | sed -e 's/\b\(.\)/\u\1/g')"
    DISTRO_LC="$(echo $DISTRO_CODENAME | sed 's/^[[:space:]]*//g')"
    MKVERSION="$(git show HEAD:VERSION | cut -d ' ' -f 1).$(git rev-list --count master)-1.git$(git rev-parse --short HEAD)~${DISTRO_LC}"
    COMMITTER="$(git show -s --pretty=%an $(git rev-parse --short HEAD))"
    EMAIL="$(git show -s --format='%ae' $(git rev-parse --short HEAD))"

    rm -f changelog
    cat > changelog <<EOF
machinekit-hal (${MKVERSION}) ${DISTRO_UC}; urgency=low

  * Cross-Builder rebuild for Debian ${DISTRO_UC}, commit $(git rev-parse --short HEAD)

 -- ${COMMITTER} <${EMAIL}>  $(date -R)

EOF

cat changelog # debug output
cat changelog.in >> changelog
echo "New package version number added to changelog"
}

## Create source orig tarball in format required for creation of debian tarball and .dsc file
## Allows non binary package builds from command line or outside Travis environment

do_source_tarball() {
#version based on major version plus commit number only, without suffixed -1 or commit hash
MK_VERSION="$(git show HEAD:VERSION | cut -d ' ' -f 1).$(git rev-list --count master)"

OWD=$PWD
cd ../
git archive HEAD | bzip2 -z > ../machinekit-hal_${MK_VERSION}.orig.tar.bz2
echo "Source tarball created"
cd $OWD
}

usage() {
    {
	test -z "$1" || echo "$1"
	echo "Usage:  $0 [ arg ... ]"
	echo "   arg:		function:"
	echo "   -p		build POSIX threads"
	echo "   -r		build RT_PREEMPT threads"
	echo "   -x		build Xenomai threads"
	echo "   -c		rewrite changelog to set package version from git commit"
	echo "	 -s		create source tarball for non binary package builds"
	echo "      *** Argument may be repeated for multiple kernels"
    } >&2
    exit 1
}
test "$1" != --help || usage

#############################################
# Main program
#
# These need to be in a certain order:
# - Base template copy first
# - do_<flavor> functions next
# - replace BUILD_DEPS and *_KERNEL_HEADERS last
#   (when lists are fully populated)

# set defaults
BUILD_DEPS=  # List of Build-Depends
DEPS= # List of Depends
HAVE_FLAVOR=false
HAVE_KTHREADS_FLAVOR=false

cp control.d/control.in control
echo "debian/control:  copied base template" >&2

cp postinst.in machinekit-hal-posix.postinst
cp postinst.in machinekit-hal-rt-preempt.postinst
cp postinst.in machinekit-hal-xenomai.postinst

cp rules.in rules; chmod +x rules
echo "debian/rules:  copied base template" >&2

cp changelog.in changelog
echo "debian/rules:  copied base changelog" >&2

# read command line options - d is a dummy to stop args being req
while getopts csprxd:?h ARG; do
    case $ARG in
	p) do_posix ;;
	r) do_rt-preempt ;;
	x) do_xenomai ;;
	c) do_changelog ;;  # set new changelog with package versions from git
	s) do_source_tarball ;; # create tarball for non binary builds
	?|h) usage ;;
	*) usage "Unknown arg: '-$ARG'" ;;
    esac
done

# Set control Build-Depends:
sed -i control \
    -e "s/@BUILD_DEPS@/${BUILD_DEPS}/" \
    -e "s/@DEPS@/${DEPS}/"
echo "debian/control:  add final Build-Depends: list" >&2

# Warn if no flavor configured
$HAVE_FLAVOR || usage "WARNING:  No thread flavors configured"
	