#!/bin/sh
#
# Make whichever packages the system supports
#
# Copyright (c) 2012-2017,2022 Red Hat.
# Copyright (c) 2004 Silicon Graphics, Inc.  All Rights Reserved.
#
# 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.
#

topdir=`pwd`
signed=false
verbose=false
cibuild=false
srconly=false
cfgonly=false
dorpm=unknown
dodeb=unknown
check=false

if [ ! -d .git ]
then
    echo "Error: can only be run from the top of a PCP git repository"
    exit 1
fi

if [ ! -f VERSION.pcp ]
then
    echo "Error: can only be run from the top of the PCP source tree"
    exit 1
fi

# set SOURCE_DATE_EPOCH for tools like rpmbuild
STRING_DATE_EPOCH=`date +%s`; export STRING_DATE_EPOCH
SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-$STRING_DATE_EPOCH}"; export SOURCE_DATE_EPOCH

# Optional local patching ... maybe required for vendor code when we're
# waiting for an upstream fix that's otherwise killing the build.
# If the script local.patch exists it is per-host and *NOT* expected
# to be in the git tree.
#
[ -x local.patch ] && ./local.patch

# put VERSION.pcp back, remove temp files and exit
#
_cleanup()
{
    cd $topdir
    if [ -f VERSION.pcp ]
    then
	if [ -z "`git status -s VERSION.pcp`" ]
	then
	    # nothing to fix
	    :
	else
	    echo "Reinstate VERSION.pcp ..."
	    if git checkout -- VERSION.pcp
	    then
		# ok
		:
	    else
		echo "Hmm, exit status $? from git checkout"
		echo "pwd=`pwd` topdir=$topdir"
		ls -l VERSION.pcp
		git status -s -- VERSION.pcp
	    fi
	fi
    else
	echo "Botch: VERSION.pcp vanished from $topdir"
	git checkout -- VERSION.pcp
    fi
    # Optional undo local patching
    #
    [ -x local.patch ] && ./local.patch --undo
    rm -rf $tmp
}

topdir=`pwd`
tmp=`mktemp -d /tmp/pcp.XXXXXXXXX` || exit 1
sts=1		# failure is the default
trap "_cleanup; exit \$sts" 0 1 2 3 15
target=`uname -s | tr 'A-Z' 'a-z'`

# Find where a GNU tool is hiding, look for this line in the
# $gnutool --help output ...
# "Report bugs to <bug-$gnutool@gnu.org>"
# or lines like this:
# FreeBSD $gnutool
# NetBSD $gnutool
# OpenBSD $gnutool
# Apple $gnutool
# or these lines:
# *This* tar defaults to:
# --format=gnu ... or --format=posix
#
gnu_tool()
{
    prefix="$1"
    shift
    envvar="$1"
    shift
    oldcmd="$1"
    shift

    # Not in the environment, go search for it in the known locations.
    #
    if [ -z "$envvar" ]
    then
	for command in $oldcmd $@
	do
	    exec=`which $command 2>/dev/null`
	    if [ -n "$exec" ]
	    then
		LC_ALL=C $command --help >$tmp/help 2>&1
		if grep -E "(bug-$oldcmd@gnu.org)|(FreeBSD $command)|(NetBSD $command)|(OpenBSD $command)|(Apple $command)" $tmp/help >/dev/null
		then
		    echo $exec
		    return 0
		fi
		awk <$tmp/help >$tmp/check '
BEGIN				{ want = 0 }
/This\** tar defaults to:/	{ want=1; next }
want == 1			{ print; exit }'
		if grep -E '[-][-]format=(gnu)|(posix)' <$tmp/check >/dev/null
		then
		    echo $exec
		    return 0
		fi
		# special cases
		#
		if [ "$target" = openbsd -a $command = gzip ]
		then
		    echo $exec
		    return 0
		fi
	    fi
	done
	echo >&2 "$prefix: can't find GNU $oldcmd in the commands $oldcmd or $@"
	[ $prefix = Error ] && exit
	return 1
    fi

    # Use the environment request and ensure it is a full path (do not
    # change this behaviour, it is required for backward-compatibility
    # - QA failures will result if you choose to ignore this warning).
    #
    command=`which $envvar 2>/dev/null`
    if [ -z "$command" ]
    then
	echo >&2 "$prefix: $oldcmd (from the environment) does not exist!"
	[ $prefix = Error ] && exit
	return 1
    fi
    echo $command
    return 0
}

MAKE=`gnu_tool Error "$MAKE" make gmake`; export MAKE
TAR=`gnu_tool Warning "$TAR" tar gtar gnutar`; export TAR
ZIP=`gnu_tool Error "$ZIP" gzip gnuzip`; export ZIP

# check if tar supports --transform else we must use git-archive later on (e.g. RHEL5)
[ -n "$TAR" ] && $TAR --help | 2>&1 grep -q transform || USE_GIT_ARCHIVE=1
#debug# echo TAR=$TAR USE_GIT_ARCHIVE=$USE_GIT_ARCHIVE

if [ ! -x ./configure ]
then
    echo "Arrgh! cannot find the configure script"
    exit
fi
configure=./configure
cmdline_configopts=''

# our default is to build without -DNDEBUG, so assert()s are active.
# use --nodebug to change this.
#
configure_opts="--with-non-debug=no"
export configure_opts

for opt in $*
do
    [ -z "$*" ] && break

    case "$opt" in
    -clean|--clean)
	# we always clean nowadays, so silently ignore
	shift
	;;
    -verbose|--verbose)
	verbose=true
	shift
	;;
    -ci|--ci)
	cibuild=true
	shift
	;;
    --check)
	check=true
	shift
	;;
    --nonrpm)
	dorpm=false
	shift
	;;
    --nondeb)
	dodeb=false
	shift
	;;
    --signed)
	signed=true
	shift
	;;
    --source)
	srconly=true
	shift
	;;
    --configure)
	cfgonly=true
	shift
	;;
    --target)
	target=$2
	shift 2
	;;
    --with-make)
	MAKE=$2
	shift 2
	;;
    --with-tar)
	TAR=$2
	shift 2
	;;
    --with-zip)
	ZIP=$2
	shift 2
	;;
    --nodebug)
	configure_opts="--with-non-debug=yes"
	;;
    *)
	# Add remaining options to the ./configure command line
	cmdline_configopts="$cmdline_configopts $opt"
	shift
	;;
    esac
done

if [ $dorpm = unknown ]
then
    dorpm=false
    if which slackpkg >/dev/null 2>&1
    then
	# Slackware has rpm(1) and rpmbuild(1), but don't build RPMs
	#
	:
    elif which mx-boot-repair >/dev/null 2>&1
    then
	# MX Linux has rpm(1) and rpmbuild(1), but don't build RPMs
	#
	:
    else
	[ -x /usr/bin/rpmbuild ] && dorpm=true
    fi
fi
if [ $dodeb = unknown ]
then
    dodeb=false
    [ -x /usr/bin/dpkg-buildpackage ] && dodeb=true
fi

# Hmm ...
#
if $dodeb && $dorpm
then
    echo >&2 "Do not know how to build RPM and Debian packages at the same time!"
    echo >&2 "Suggest --nonrpm or --nondeb on the command line."
    exit
fi

configenv=''
if $dodeb
then
    # On Debian-based platforms, the debian/rules file already captures
    # most of the required configure settings in $(configure_paths) and
    # $(configure_tools)
    #
    configopts=''
elif $dorpm
then
    # On RPM-based platforms, rpm macros provide an excellent set of defaults.
    # This set is based on Fedora 22 %configure macro from /usr/lib/rpm/macros,
    # and is known to work as far back as RHEL5.
    configopts="`rpmbuild --eval '--exec-prefix=%{_exec_prefix} --bindir=%{_bindir} --sbindir=%{_sbindir} --sysconfdir=%{_sysconfdir} --datadir=%{_datadir} --includedir=%{_includedir} --libdir=%{_libdir} --libexecdir=%{_libexecdir} --localstatedir=%{_localstatedir} --sharedstatedir=%{_sharedstatedir} --mandir=%{_mandir} --prefix=%{_prefix}' 2>/dev/null`"
    # rpmbuild clears the environment, so force these settings into the
    # rpm build configure
    #
    configopts="$configopts --with-make=$MAKE --with-tar=$TAR --with-zip=$ZIP"
    # for RHEL 6 and CentOS 6, building with selinux no longer works, and
    # our libqwt won't build
    #
    if [ -f /etc/system-release ]
    then
	if grep -E '((Red Hat)|CentOS).* release 6\.' /etc/system-release >/dev/null
	then
	    configopts="$configopts --with-selinux=no --with-qt=no"
	fi
    fi
elif [ $target = darwin ]
then
    # On Mac OS platforms, we install away from /usr/bin, /usr/lib
    # and so on because of security requirements in recent versions.
    # Qt use is retired here due to problems with linking+packaging.
    # The realpath invocations resolve an issue relating to symlink
    # re-mapping to the /private paths.
    #
    etc=`realpath /etc`
    var=`realpath /var`
    configopts="--sysconfdir=$etc --localstatedir=$var --prefix=/usr/local --with-qt=no"
    PKGBUILD=`which pkgbuild`; export PKGBUILD
elif [ $target = netbsd ]
then
    # Try to mimic where pkgsrc/pkgin places things
    #
    configopts="--exec-prefix=/usr/pkg --mandir=/usr/pkg/man --with-rcdir=/etc/rc.d --localstatedir=/usr/pkg --with-rundir=/var/run --with-tmpdir=/var/tmp --with-logdir=/var/log/pcp --prefix=/usr/pkg"
elif [ $target = freebsd ]
then
    # Python build does not work on FreeBSD 9.3, so skip it
    # For FreeBSD 10.4 and 11.3 it seems to fail when trying to build
    # Python and Python3 at the same time ... so skip Python(2)
    # For FreeBSD 13 I don't have Qt working
    # For FreeBSD 14 cppcheck => Qt installed
    #
    case `uname -r`
    in
	9.3*)
		# Bog-standard, just without python3
		#
		configopts="--sysconfdir=/etc --localstatedir=/var --prefix=/usr --with-python3=no"
		;;
	13.*)
		# Bog-standard, just without Qt
		#
		configopts="--sysconfdir=/etc --localstatedir=/var --prefix=/usr --with-qt=no"
		;;
	*)
		# Bog-standard, as below ...
		#
		configopts="--sysconfdir=/etc --localstatedir=/var --prefix=/usr"
		;;
    esac
else
    # Bog-standard options suitable for a package on any platform.
    # Command line can be used to extend this set, and any unusual
    # platform-specific requirements are also appended later on.
    configopts="--sysconfdir=/etc --localstatedir=/var --prefix=/usr"
fi

# Platform-specific variants ...
#
case "$target"
in
    mingw|mingw64|windows)
	target=mingw
	dorpm=false
	configopts="$configopts --disable-ssp --without-python3"
	configure="/usr/bin/mingw64-configure"; export configure
	MAKE="/usr/bin/mingw64-make"; export MAKE
	QMAKE="/usr/bin/mingw64-qmake-qt6"; export QMAKE
	PKG_CONFIG="/usr/bin/mingw64-pkg-config"; export PKG_CONFIG
	;;
    linux)
	ARCH=`uname -m`
	[ -f /etc/slackware-version -a "$ARCH" = x86_64 ] && configopts="$configopts --libdir=/usr/lib64"
	;;
    sunos|SunOS|solaris)
	ARCH=`isainfo -k`
	[ "$ARCH" = amd64 -o "$ARCH" = sparcv9 ] && configopts="$configopts --libdir=/usr/lib/64"
	YACC=bison; export YACC
	LEX=flex; export LEX
	;;
esac

# now some specific QA/development hosts with special needs ...
#
case `hostname`
in
    vm11|vm11.localdomain)
	# gcc -O2 is broken here (for the linux PMDA)
	#
	configopts="$configopts --with-optimization=no"
	# over-ride the settings from dpkg-buildflags
	#
	DEB_CFLAGS_SET=''; export DEB_CFLAGS_SET
	DEB_CXXFLAGS_SET=''; export DEB_CXXFLAGS_SET
	;;
esac

# and finally add in any from the command line
#
[ -n "$cmdline_configopts" ] && configopts="$configopts $cmdline_configopts"

# Grep pattern for --ci mode: phase headers, errors, and make failures.
CI_LOG_RE='(^==|[Ee]rror[: ]|[Ff]ailed|[Ff]atal[: ]|make(\[[0-9]+\])?: \*\*\*)'

# Tee build output to $LOGDIR/pcp, streaming to stdout based on mode:
#   verbose  - stream everything (full tee)
#   cibuild  - stream only lines matching CI_LOG_RE
#   default  - silent; full output goes to log only
#
_tee_log()
{
    if $verbose ; then
	tee -a "$LOGDIR/pcp"
    elif $cibuild ; then
	# grep exits 1 if no lines match; that is harmless here since
	# build failure is detected via $tmp/failed, not pipeline status.
	tee -a "$LOGDIR/pcp" | grep -E "$CI_LOG_RE" || true
    else
	cat >> "$LOGDIR/pcp"
    fi
}

build_failure()
{
    if $cibuild ; then
	echo "$@ failed, see log in $LOGDIR/pcp"
	echo "=== Error summary ==="
	grep -n -E "$CI_LOG_RE" "$LOGDIR/pcp" | tail -20
	echo "=== Last 100 lines ==="
	tail -100 "$LOGDIR/pcp"
    elif ! $verbose ; then
	echo "$@ failed, see log in $LOGDIR/pcp"
	tail "$LOGDIR/pcp"
    fi
    exit
}

# VERSION.pcp.dev is the same as VERSION.pcp except the PACKAGE_BUILD
# value increases each time Makepkgs is run and VERSION.pcp.dev will
# be used in place of VERSION.pcp for this build
#
bump_build_number()
{
    if [ ! -f VERSION.pcp.dev ]
    then
	# first build, ever
	#
	cp VERSION.pcp VERSION.pcp.dev
    else
	diff VERSION.pcp VERSION.pcp.dev >$tmp/tmp
	if grep -q -E 'PACKAGE_MAJOR|PACKAGE_MINOR|PACKAGE_REVISION' <$tmp/tmp
	then
	    # different PCP release, do an initial build
	    #
	    cp VERSION.pcp VERSION.pcp.dev
	else
	    # same PCP release as last build, bump away
	    awk -F= <VERSION.pcp.dev '
BEGIN			{ OFS = "=" }
$1 == "PACKAGE_BUILD"	{ print "PACKAGE_BUILD",$2+1; next }
			{ print }' \
	    | sed -e 's/=$//' >$tmp/tmp
	    cp $tmp/tmp VERSION.pcp.dev
	fi
    fi
    cp VERSION.pcp.dev VERSION.pcp
}

clean_packaging()
{
    echo
    echo "== Cleaning build tree for packaging build"
    rm -rf "$SRCDIR" "$SRCTAR"
}

fix_version()
{
    if [ -f "$1" -a -f "$2" ]
    then
	# as expected, both present
	if diff "$1" "$2" >/dev/null 2>&1
	then
	    :
	else
	    # must be using git-archive(1) and VERSION.pcp has been
	    # modified, e.g. by pcp-daily script ... use the modified
	    # one to bump the build number in the packages
	    #
	    cp "$1" "$2"
	fi
    else
	echo "Arrgh ... expect both these to exist ..."
	ls -l "$1" "$2"
	exit
    fi
}

# Generate a list of all the files git knows about, create the
# source tarball and then unpack it.  We'll then do the package
# build in a guaranteed pristine environment.
#
src_tar_build()
{
    if [ -z "$TAR" -o ! -z "$USE_GIT_ARCHIVE" ]
    then
	# no suitable GNU tar is available, use git-archive(1) - no local changes
	if git status -s src man | grep '^.M'
	then
	    echo "Arrgh, modified src files and either no tar ($TAR) or no --transform"
	    echo "support in tar, so local changes would not be included in the build."
	    exit
	fi
	git archive --format=tar --prefix=$source/ HEAD | $ZIP > "$SRCTAR"
    else
	# build git file list and make tarball by hand to pick up any changes
	#
	git ls-files >$tmp.gitcensus
	if [ -f .gitattributes ]
	then
	    # pick entries with the export-ignore attribute
	    # and cull $tmp.gitcensus
	    #
	    sed -n <.gitattributes >$tmp.sed \
		-e '/^#/d' \
		-e '/ export-ignore/{
s/ export-ignore//
s;/;\\/;g
s;\*;.*;g
s;^;/;
s;$;/d;
p
}' \
	    # end
	    if [ -s $tmp.sed ]
	    then
		sed -f $tmp.sed <$tmp.gitcensus >$tmp.tmp
		mv $tmp.tmp $tmp.gitcensus
	    fi
	    rm -f $tmp.sed
	fi

	# add debian/control ... will be replaced later
	#
	[ -f debian/control ] || touch debian/control
	echo "debian/control" >>$tmp.gitcensus

	$TAR -cz --transform="s,^,$source/,S" --files-from=$tmp.gitcensus \
		--file="$SRCTAR"
	rm -f $tmp.gitcensus
    fi
    echo "Wrote: $SRCTAR"
}

# On sanity checks :- this is sick, but I'm really tired of QA failing
# because of bad binaries being built from the Debian/Ubuntu toolchain
# for # i?86 platforms
# - Ken McDonell Apr 2010
#
sanity_check_settings()
{
    OPT=false
    ARCH=`uname -m | sed -e 's/i.86/ia32/'`
    if [ "$ARCH" != "ia32" ]
    then
	OPT=true	# no workarounds needed for non-i?86 platforms
    elif [ -f /etc/lsb-release ]
    then
	if grep -q 'DISTRIB_ID=Ubuntu' /etc/lsb-release
	then
	    eval `grep DISTRIB_RELEASE= /etc/lsb-release`
	    XDISTRIB_RELEASE=`echo $DISTRIB_RELEASE | sed -e 's/[^0-9]//g'`
	    [ -z "$XDISTRIB_RELEASE" ] && XDISTRIB_RELEASE=0000
	    if [ $XDISTRIB_RELEASE -gt 1110 ]
	    then
		# Hope the problem is fixed after Ubuntu 11.10
		OPT=true
	    fi
	fi
	$OPT || echo "Building without optimization for Ubuntu $DISTRIB_RELEASE"
    elif [ -f /etc/debian_version ]
    then
	DISTRIB_RELEASE=`cat /etc/debian_version`
	XDISTRIB_RELEASE=`echo $DISTRIB_RELEASE | sed -e 's/[^0-9]//g'`
	[ -z "$XDISTRIB_RELEASE" ] && XDISTRIB_RELEASE=0000
	if [ $XDISTRIB_RELEASE -ge 700 ]
	then
	    # Hope the problem is fixed in Debian 7.0.0
	    OPT=true
	fi
	$OPT || echo "Building without optimization for Debian $DISTRIB_RELEASE"
    fi

    if ! $OPT
    then
	ok=true
	if grep -q '^my $default_flags .*O2' /usr/bin/dpkg-buildpackage
	then
	    echo 'dpkg-buildpackage: need to remove O2 from $default_flags'
	    ok=false
	fi
	if grep -q '^[ 	]*LDFLAGS.*-Bsymbolic-functions' /usr/bin/dpkg-buildpackage
	then
	    echo 'dpkg-buildpackage: need to remove -Bsymbolic-function from LDFLAGS'
	    ok=false
	fi
	if ! $ok
	then
	    echo "Refer to Debian/Ubuntu notes in PCP's ./INSTALL"
	    exit
	fi
	# as of Debian 6.0.1 and Ubuntu 10.10, build flags are hidden and
	# extracted using dpkg-buildflags which fortunately honours some
	# environment variable settings
	#
	DEB_CFLAGS_SET=''; export DEB_CFLAGS_SET
	DEB_CXXFLAGS_SET=''; export DEB_CXXFLAGS_SET
	DEB_LDFLAGS_SET=''; export DEB_LDFLAGS_SET
    fi
}

# Build Debian packages using the dpkg-buildpackage utility which runs
# the complete build, from configure through to final deb preparation.
#
debian_buildpackage()
{
    echo
    echo "== Building deb packages using dpkg-buildpackage"

    SUDO=${SUDO:-fakeroot}
    TYPE=${TYPE:-source}      # alternate: full
    sign='-us -uc'	# don't sign by default
    # sign if --signed and $DEB_SIGN_KEYID set in the environment
    # (usual for an upload to Debian servers, so its source-only
    # - unless new sub-packages exist then we need full build)
    $signed && [ -n "$DEB_SIGN_KEYID" ] && sign="--build=$TYPE"
    opts="$sign -r$SUDO -sa"

    # let dpkg-buildpackage sort out SOURCE_DATE_EPOCH
    #
    unset SOURCE_DATE_EPOCH

    rm -f $tmp/failed
    (dpkg-buildpackage $opts || touch $tmp/failed) 2>&1 | _tee_log
    [ -f $tmp/failed ] && build_failure dpkg-buildpackage
}

prepare_debian_sources()
{
    # shortcut for dpkg-buildpackage which does everything itself from here
    rm -rf "$SRCDIR"
    mkdir -p "$SRCDIR" 2>/dev/null

    cd "$SRCDIR" || exit
    $TAR -zxf "$SRCTAR" || exit
    cd "$SRCTREE" || exit

    fix_version "$topdir"/VERSION.pcp VERSION.pcp

    # make changelog match version
    #
    if [ ! -f debian/changelog ]
    then
	echo "Arrgh! No debian/changelog below `pwd`"
	exit
    fi
    if head -1 debian/changelog | grep -q "^pcp ($PACKAGE_MAJOR.$PACKAGE_MINOR.$PACKAGE_REVISION-"
    then
	# correct package version, fix $PACKAGE_BUILD
	#
	sed -i -e "1s/-[0-9][0-9]*)/-$PACKAGE_BUILD)/" debian/changelog
    else
	# new|different version, add dummy stanza for this (developer build)
	#
	[ -z "$GIT_AUTHOR_NAME" ] && GIT_AUTHOR_NAME="Bozo the Clown"
	[ -z "$GIT_AUTHOR_EMAIL" ] && GIT_AUTHOR_EMAIL="bozo@kenj.id.au"
	cat <<End-of-File >$tmp/changelog
pcp ($PACKAGE_MAJOR.$PACKAGE_MINOR.$PACKAGE_REVISION-$PACKAGE_BUILD) unstable; urgency=low

  * Developer build.

 -- $GIT_AUTHOR_NAME <$GIT_AUTHOR_EMAIL>  `date -R`

End-of-File
	cat debian/changelog >>$tmp/changelog
	cp $tmp/changelog debian/changelog
    fi
}

prepare_debian_control()
{
    echo
    echo "== Preparing source tree for dpkg-buildpackage"
    parent=`realpath ..`
    orig="$parent/pcp_$VERSION.orig.tar"
    mv "$SRCTAR" "$orig.gz"
    echo "Renamed: $SRCTAR -> $orig.gz"
    # now we've run configure in this build tree, so now we can
    # remake debian/control and update the source tarball
    #
    rm -f $tmp/failed debian/control
    ($MAKE -C debian control 2>&1 || touch $tmp/failed) 2>&1 | _tee_log
    [ -f $tmp/failed ] && build_failure debian control
    $ZIP -d "$orig.gz"
    $TAR -f "$orig" --delete "$source/debian/control"
    $TAR -f "$orig" --transform="s,^,$source/,S" --append debian/control
    $ZIP "$orig"
    echo "Replaced: debian/control in $orig.gz"
}

debian_build()
{
    SRCDIR="$topdir/build/deb"
    SRCTREE="$topdir/build/deb/$source"
    prepare_debian_sources

    # Note: we need to run configure here to get things like builddefs
    #       created, but configure will be run _again_ from
    #       debian_buildpackage, but we need to make sure the same
    #       configure options are used in both places
    #
    configure_opts="$configopts"; export configure_opts
    if [ ! -f debian/rules ]
    then
	echo "Botch: cannot find debian/rules"
	exit
    fi
    debian_paths=`sed -n <debian/rules -e '/^configure_paths/s/^[^=]*= *//p'`
    if [ -z "$debian_paths" ]
    then
	echo "Botch: cannot get config options from configure_paths in debian/rules"
	exit
    fi
    configopts="$debian_paths $configopts"
    debian_env=`sed -n <debian/rules -e '/^configure_tools/{
s/^[^=]*= *//
s/export *//
s/;//
p
}'`
    if [ -z "$debian_env" ]
    then
	echo "Botch: cannot get env settings from configure_tools in debian/rules"
	exit
    fi
    configenv="$debian_env"
    configure_pcp
    prepare_debian_control
    sanity_check_settings
    debian_buildpackage
    check_pcp

    # success!
    if ! $verbose ; then
	grep ^dpkg-deb "$LOGDIR/pcp" | \
	    sed -e 's,\.$,,g' -e "s,',,g" -e "s,\.\.,$topdir/build/deb,g" | \
	    awk '{ print "Wrote:", $NF }'
    fi
    sts=0
    exit
}

prepare_build()
{
    echo
    echo "== Preparing fresh build tree for packaging build"

    if [ ! -d "$SRCDIR" ]; then
	# extract gzipped tar archive
	$TAR -xz --file="$SRCTAR" || exit
	fix_version VERSION.pcp "$SRCDIR"/VERSION.pcp
    fi
}

configure_pcp()
{
    echo
    echo "== Configuring pcp, log is in $LOGDIR/pcp $configenv ($configopts)"
    [ -n "$configenv" ] && export $configenv

    rm -f $tmp/failed
    ($configure $configopts 2>&1 || touch $tmp/failed) 2>&1 | _tee_log
    if [ -f src/include/pcp/autoheader-dummmy.h ]
    then
	# dodge autoheader(1) interference with configure.ac
	# ... this file is created by configure.ac, but we don't
	# want it included in the source tree handed to dpkg-buildpackage
	# (it is irrelevant for all builds, not just the Debian ones)
	#
	rm -f src/include/pcp/autoheader-dummmy.h
    fi
    if [ -f $tmp/failed ]
    then
	test -f config.log && cat config.log | _tee_log
	build_failure Configure
    fi
    if $cfgonly
    then
	sts=0
	exit
    fi
}

check_pcp()
{
    $check || return 0

    echo
    echo "== Checking pcp, log is in $LOGDIR/pcp" | tee -a "$LOGDIR/pcp"

    rm -f $tmp/failed
    ($MAKE check 2>&1 || touch $tmp/failed) 2>&1 | _tee_log
    [ -f $tmp/failed ] && build_failure Checking
}

default_build()
{
    echo
    echo "== Building pcp, log is in $LOGDIR/pcp"

    rm -f $tmp/failed
    ($MAKE default_pcp 2>&1 || touch $tmp/failed) 2>&1 | _tee_log
    [ -f $tmp/failed ] && build_failure Make default_pcp
}

packaging_pcp()
{
    echo
    echo "== Packaging pcp, log is in $LOGDIR/pcp" | tee -a "$LOGDIR/pcp"

    rm -f $tmp/failed
    ($MAKE -C build pack_pcp 2>&1 || touch $tmp/failed) 2>&1 | _tee_log
    [ -f $tmp/failed ] && build_failure Packaging via pack_pcp
}

packaging_rpm()
{
    echo
    echo "== Building rpm packages, log is in $LOGDIR/pcp" | tee -a "$LOGDIR/pcp"

    rm -f $tmp/failed
    DIST_ROOT="$topdir/build/rpm/$source"; export DIST_ROOT
    # sign if --signed and $RPM_SIGN_KEYID set in the environment
    $signed && [ -z "$RPM_SIGN_KEYID" ] && unset RPM_SIGN_KEYID
    ($MAKE -C build/rpm pack_pcp 2>&1 || touch $tmp/failed) 2>&1 | _tee_log
    [ -f $tmp/failed ] && build_failure Packaging RPMs via pack_pcp
}

# real build starts here
bump_build_number

. ./VERSION.pcp
VERSION=${PACKAGE_MAJOR}.${PACKAGE_MINOR}.${PACKAGE_REVISION}

LOGDIR="$topdir/Logs"
rm -rf "$LOGDIR"
mkdir -p "$LOGDIR"

source="pcp-$VERSION"
SRCDIR="$topdir/$source"
SRCTREE="$topdir/$source"
SRCTAR="$topdir/build/tar/$source.src.tar.gz"

clean_packaging
src_tar_build
if $srconly
then
    sts=0
    exit
fi

# short-circuit for performing builds with dpkg-buildpackage
if $dodeb
then
    debian_build
    # NOTREACHED
fi

prepare_build

# shift into the clean packaging build tree from here onward
cd "$SRCDIR"

configure_pcp

# short-circuit for performing rpm-only builds with rpmbuild
# (skips over the default_build stage as rpmbuild does that).
if $dorpm
then
    packaging_rpm
else
    default_build	# perform a complete build in-situ
    packaging_pcp	# create all known package formats
fi

#
# At this point we may, or may not be in a build tree (no for rpm,
# yes for debian, who knows for others) ... so anything that is a
# build artifact that is needed by "make check" may not be there,
# so there are some explicit things than may need to be made.
#
# The "dir" list below was hand-crafted based on historical build
# failures, but as of now (4 May 2021) we don't have any specific
# requirements, so this list is empty.
#
here=pwd
for dir in
do
    if [ ! -d "$dir" ]
    then
	echo "Error: \"make check\" setup: $dir not found"
	exit
    fi
    cd $dir
    make
    cd $here
done

check_pcp		# static checking (should be last).

# success!
if ! $verbose ; then
    grep '^Wrote:' "$LOGDIR/pcp" | sed -e 's/\.\.\/\.\.\///'
fi

sts=0
exit
