#! /bin/bash -
# Specific script for the final Dragora release process.
#
# Copyright (c) 2021-2022 Matias Fonzo, <selk@dragora.org>.
#
# 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.

#
## ChangeLog (current version is 0.2).
#
#= Version 0.3:
#
# - Use the -f (force) option when building on the phase1.
#
#= Version 0.2:
#
# - Switch /bin/sh to /bin/bash for catching errors on pipes.
#
# - Upgrade packages on 'phase-2' to ensure no dependency on
#   /tools (temporary system) or to ensure possible system
#   breaks by cutting symbolic links using qi/graft.
#
#= Version 0.1:
#
# - Initial version.
#

set -e -o pipefail

rm -f /build-phase1-log.txt /build-phase2-log.txt

#
# Build all the packages to conform the final system.
#

echo ""
echo "*** Building Dragora for release [phase-1]..."
echo ""
echo "Using 1 parallel job for the compiler."
echo ""

qi order /usr/src/qi/recipes/*.order | \
 qi build -f -j1 -p -i - 2>&1 | tee build-phase1-log.txt

#
# Build all the important packages against the final system
#

# Variables.
#
# Parallel jobs for the final system (phase-2)
#
# The default is to use the maximum number of
# processors (physical/threading)
JOBS="${JOBS:-$(nproc)}"

# Declare recipes that do not require reconstruction:
exclude_list='!/pass-?|^data\/|docbook\/|xorg\/doc\/|xorg\/font\/|tde\/tde-i18n|devel\/fortify-headers|kernel\/headers|kernel\/generic|kernel\/buildtree-generic|kernel\/firmware|tools\/dragora-installer/'

echo ""
echo "*** Building Dragora for release [phase-2]..."
echo ""
echo "Using $JOBS parallel job(s) for the compiler."
echo ""

if test -d /tools
then
    mv -f /tools /tools-to-be-renamed
    sync
fi

qi order /usr/src/qi/recipes/*.order | awk "$exclude_list" | \
 qi build -f -j${JOBS} -p -u - 2>&1 | tee build-phase2-log.txt

unset -v JOBS exclude_list

if test -d /tools-to-be-renamed
then
    mv -f /tools-to-be-renamed /tools
    sync
fi

echo ""
echo "^^^ Done."
echo ""

