#!/bin/bash

set -eu

[ -e /etc/debian/debug ] && set -x

#############################################################################
# Reset
Color_Off='\033[0m'       # Text Reset

# Regular Colors
Black='\033[0;30m'        # Black
Red='\033[0;31m'          # Red
Green='\033[0;32m'        # Green
Yellow='\033[0;33m'       # Yellow
Blue='\033[0;34m'         # Blue
Purple='\033[0;35m'       # Purple
Cyan='\033[0;36m'         # Cyan
White='\033[0;37m'        # White

# Bold
BBlack='\033[1;30m'       # Black
BRed='\033[1;31m'         # Red
BGreen='\033[1;32m'       # Green
BYellow='\033[1;33m'      # Yellow
BBlue='\033[1;34m'        # Blue
BPurple='\033[1;35m'      # Purple
BCyan='\033[1;36m'        # Cyan
BWhite='\033[1;37m'       # White

# Underline
UBlack='\033[4;30m'       # Black
URed='\033[4;31m'         # Red
UGreen='\033[4;32m'       # Green
UYellow='\033[4;33m'      # Yellow
UBlue='\033[4;34m'        # Blue
UPurple='\033[4;35m'      # Purple
UCyan='\033[4;36m'        # Cyan
UWhite='\033[4;37m'       # White

# Background
On_Black='\033[40m'       # Black
On_Red='\033[41m'         # Red
On_Green='\033[42m'       # Green
On_Yellow='\033[43m'      # Yellow
On_Blue='\033[44m'        # Blue
On_Purple='\033[45m'      # Purple
On_Cyan='\033[46m'        # Cyan
On_White='\033[47m'       # White

# High Intensity
IBlack='\033[0;90m'       # Black
IRed='\033[0;91m'         # Red
IGreen='\033[0;92m'       # Green
IYellow='\033[0;93m'      # Yellow
IBlue='\033[0;94m'        # Blue
IPurple='\033[0;95m'      # Purple
ICyan='\033[0;96m'        # Cyan
IWhite='\033[0;97m'       # White

# Bold High Intensity
BIBlack='\033[1;90m'      # Black
BIRed='\033[1;91m'        # Red
BIGreen='\033[1;92m'      # Green
BIYellow='\033[1;93m'     # Yellow
BIBlue='\033[1;94m'       # Blue
BIPurple='\033[1;95m'     # Purple
BICyan='\033[1;96m'       # Cyan
BIWhite='\033[1;97m'      # White

# High Intensity backgrounds
On_IBlack='\033[0;100m'   # Black
On_IRed='\033[0;101m'     # Red
On_IGreen='\033[0;102m'   # Green
On_IYellow='\033[0;103m'  # Yellow
On_IBlue='\033[0;104m'    # Blue
On_IPurple='\033[0;105m'  # Purple
On_ICyan='\033[0;106m'    # Cyan
On_IWhite='\033[0;107m'   # White

#############################################################################
# Command line options (with defaults).
option_architecture=$(dpkg-architecture -qDEB_BUILD_ARCH)
option_do_commit=false
option_update_dch=true
option_do_upload=false
option_force_upload=false
option_additional_packages="debian-keyring"
option_mirror=http://deb.debian.org/debian/
option_profile=
option_keyring=/usr/share/keyrings/debian-archive-keyring.gpg

option_release=bullseye
option_repository=
option_suite="unstable"

option_update_chroot=true
option_skip_tests=false
option_source_only=false
option_silent=false
option_debug=false
option_version=
option_pdebuild=
option_build_branch="master"

apt_preferences=
lintian_profile=
builder_release=
# FIXME: allow making the architecture configurable (for building 32-bit
# and 64-bit packages). Once an autobuilder is in place, and if this is
# still needed, the autobuilder will rebuild the packages for us. We do
# not need to keep track of both ourselves.
pbuildercache=/var/cache/pbuilder
pbuilder_hook=$(dirname $(readlink -f $0))
result_dir=$(readlink -f ..)
# Set other-mirror to the builder only if building for debian
other_mirror=
# The components that are used in the software repository. This defaults
# to the debian layout.
DISTRO_COMPONENTS="main contrib non-free"
return_value=0

function show_help {
  echo """
NAME
       debian-package-build - Debian Package Build, build GNU/Debian package

SYNOPSIS
       debian-package-build

DESCRIPTION
       debian-package-build is a tool that allows building debian packages
       in an isolated and discarded environment using cowbuilder.

       -a --architecture=ARCH
       Build for a different architecture than the host. Valid values
       are the Debian architecture definitions.
       At the moment, this has only been validated for building 32-bit
       on a 64 bit host.
       e.g. -a i386, --architecture=amd64

       -b --build-branch
       The branch where the official builds are built from
       e.g. -b debian/bpo/buster

       -c --commit
       Update the changelog and version based on the git history of
       the project. The short log of the commits will be used to list
       the changes.

       --clear-cache)
       Remove the local chroots. This will force debian-package-build
       to re-generate them on the next run.

       -d --debug
       Enable script debugging (set -x). This is equivalent to creating
       a file /etc/debian/debug

       -h --help
       Show this help message.

       -k --keyring)
       Package to use during creation of the chroot to include extra
       keyring.

       -m --mirror
       Mirror to use in order to download package.

       --no-chroot-update
       Do not update the chroot before building

       --no-dch
       Do not update the debian/changelog

       --profile
       The profile to use. Available profiles: $(echo $(find /usr/share/debian-package-build/profiles/ -exec basename {} \; | tail -n +2 | sort))

       -r --release=RELEASE
       The default release is bullseye. This flag allows overriding to
       another release
       e.g. -r stretch

       -s --suite=SUITE
       The suite to upload the package to (default unstable)
       e.g. -s experimental

       --skip-tests
       Skip the tests during packaging.

       -S --silent
       Do not present the changelog changes, just commit (intended for
       Jenkins use)

       -u --upload
       Upload the package to the build infrastructure

       -v  --version=version
       Set a custom version instead of incrementing debian/changelog

       --source-only
       Upload the sources to the builder without compiling it locally
       for verification.

  """
}

# am_i_root
#
# test if the script is run as root
function am_i_root {
  if [[ ${EUID} -ne 0 ]]; then
    echo "This script must be run as root" 1>&2
    exit 1
  fi
}

function clean {
  echo "Cleaning environment"
  # clear the trap
  trap - EXIT
  [ -f debian/changelog ] && [ -d .git ] && git checkout debian/changelog
}

function clean_git_directory {
  if [ "$option_silent" = true ]; then
    echo "Forceful clean up"
    git clean -d -f -x -q
  else
    echo 'Interactive cleaning up'
    git clean -d -x -i
  fi
}

function is_installed {
  # Simple helper function to test if a package is installed. If not,
  # install it (using debian package management).
  dpkg -s "$1" &> /dev/null

  if [ $? -eq 0 ]; then
    # echo "Package \"$1\"  is installed!"
    :
  else
    echo "Package \"$1\" is NOT installed, installing!"
    # Try a couple times to compensate for crappy mirrors
    for i in $(seq 10); do DEBIAN_FRONTEND=noninteractive apt-get -y install "$1" && s=0 && break || s=$? && sleep 15; done; (exit $s)
  fi
}

function load_profile {
  [ -d /usr/share/debian-package-build/profiles/ ] \
    || { echo "Could not find profile directory for ${option_profile}: /usr/share/debian-package-build/profiles/"; exit 1; }
  [ -e /usr/share/debian-package-build/profiles/${option_profile} ] \
    || { echo "Could not find profile configuration for ${option_profile}: /usr/share/debian-package-build/profiles/${option_profile}"; exit 1; }
  source /usr/share/debian-package-build/profiles/${option_profile}

  # This function load the profile that was defined and/or configured. The
  # parameters are loaded selectively at the moment. This can be simplified.
  [ -z "${PROFILE_MIRROR+x}" ] || option_mirror=${PROFILE_MIRROR}
  [ -z "${PROFILE_ADDITIONAL_PACKAGES+x}" ] || option_additional_packages=${PROFILE_ADDITIONAL_PACKAGES}
  [ -z "${PROFILE_LINTIAN_PROFILE+x}" ] || lintian_profile=${PROFILE_LINTIAN_PROFILE}
  [ -z "${PROFILE_REPOSITORY+x}" ] || option_repository=${PROFILE_REPOSITORY}
  [ -z "${PROFILE_KEYRING+x}" ] || option_keyring=${PROFILE_KEYRING}
  [ -z "${PROFILE_RELEASE+x}" ] || option_release=${PROFILE_RELEASE}
  [ -z "${PROFILE_SUITE+x}" ] || option_suite=${PROFILE_RELEASE}
}

function lintian_package_test {
  # This is a workaround for people using old lintian versions. Older
  # versions have the option --fail-on-warnings (deprecated) while they do
  # not have --fail-on that gives more fine grained control.
  #
  # The following detects this and adjusts the command line accordingly.

  if [ $(lintian -h |grep -c fail-on-warnings) -gt 0 ]; then
    # This is an old lintian. use --fail-on-warnings
    fail_on="--fail-on-warnings"
  elif [ $(lintian -h |grep -c fail-on) -gt 0 ]; then
    # This is a new lintian. use --fail-on warning
    fail_on="--fail-on warning"
  else
    # This is a pretty annoying lintian that does not know either of them.
    fail_on=""
  fi


  PROFILE=""
  [ -z "${lintian_profile}" ] || PROFILE="--profile ${lintian_profile}"

  # allow errors to catch return value
  set +e
  lintian ${fail_on} ${PROFILE} --info "${result_dir}/${debian_package}_${new_noepoch}_${option_architecture}.changes"
  r=$?
  set -e
  if [ $r != 0 ]; then
    echo -e "${BYellow}⚠️  detected lintian issues, please fix these before uploading.${Color_Off}"
    option_do_upload=false
    option_do_commit=false
    return_value=1
  fi
}

function build_package_in_chroot {
  DEB_BUILD_OPTIONS=${DEB_BUILD_OPTIONS:-}
  if [ "$option_skip_tests" = true ]; then
    # The builder will not apply this, add it in debian/rules if needed.
    echo "Adjusting DEB_BUILD_OPTIONS to skip the tests."
    DEB_BUILD_OPTIONS+=" nocheck"
    export DEB_BUILD_OPTIONS
  fi

  new_noepoch=$(echo "${new}" | cut -f 2- -d : )
  if [ "$option_source_only" = true ]; then
    echo "Source only upload of \"${debian_package}\", version ${new_noepoch} (please wait)..."
    dpkg-source -b .
    dpkg-genchanges -sa > "${result_dir}/${debian_package}_${new_noepoch}_${option_architecture}.changes"
  else
    echo "Building \"${debian_package}\" (please wait)..."
    # Fail early: when the file is not writable, the sub shell of tee
    # fails; but the entire script. By touching the file that will be used,
    # touch will return an error and let the script exit.
    build_log="${result_dir}/${debian_package}_${new}_build_${option_architecture}.log"
    touch "${build_log}"
    # Try a couple times to compensate for crappy mirrors
    echo -e "${BGreen}🤚 building with log in ${build_log}${Color_Off}"

    CPUS=`grep -c ^processor /proc/cpuinfo`
    DEB_BUILD_OPTIONS+=" parallel=${CPUS}"
    export DEB_BUILD_OPTIONS

    for i in $(seq 10); do
      pdebuild --architecture "${option_architecture}" \
        --debbuildopts '-sa' \
        --pbuilder cowbuilder \
        --buildresult "${result_dir}" \
        ${option_pdebuild} -- \
        --basepath "${local_chroot}" 2>&1 >"${build_log}" \
        && s=0 && break || s=$? && sleep 15; done; (exit $s) \
      || { cat "${build_log}" ; echo "Build failed, aborting! Log at ${build_log}" ; exit 1; }
    echo "Build successful! Log can be found at ${build_log}."
  fi
}

function test_debian_changelog {
  # Check if we're currently in a package uncompressed directory and if
  # that is the same as the package name in debian/control
  package_dir=$(basename "$PWD")
  debian_package=$(grep Source: debian/control | head -n 1 | awk '{ print $2}')
  if [[ $package_dir == *${debian_package}* ]]; then
    echo "Package \"${debian_package}\" will be built"
  fi
  echo "Detected package \"${debian_package}\"."

  if [ ! -f "debian/source/format" ]; then
    echo "Could not find debian/source/format"
  fi

  for i in $(find debian/ -type f ); do
    grep -q $'\r$' "${i}" && echo "⚠️  \"$i\" looks like a DOS file, this could cause problems."
  done

  # Update changelog with git entries since last tag
  old=$(dpkg-parsechangelog --show-field Version)
  gitver=$(git describe --tags --match='debian/*' | cut -f 3 -d / | tr - +)
  echo "Current version of ${debian_package}: \"${old}\"."
  echo "Current git version based on: \"${gitver}\"."
}

function test_dirty_tree {
  # Do not allow to upload a package with a dirty git registry. This means
  # that files are changed but not committed.
  if [ $(git diff --stat --ignore-submodules=all | wc -l) -gt 0 ]; then
    echo -e "${BYellow}Build with dirty git index, disabling commit and upload.${Color_Off}"
    option_do_commit=false
    option_do_upload=false
    option_do_version=
    option_silent=false
  fi
}

function test_existing_git_tag {
  # do not exit on failure since the return value is used for test
  set +e
  git rev-list "${git_tag}".. &> /dev/null
  tag_found=$?
  set -e

  [ ${tag_found} -ne 0 ] || { echo "Trying to tag with ${git_tag} that already exists."; exit 1; }
}

function upload_package_to_builder {
  if [ "$option_do_commit" = true ]; then
    # Now commit and tag new version
    echo "new ${debian_package} version: ${new}"
    if [ -d .git ]; then
      git commit -m "changelog: updated version to ${new}" debian/changelog
      the_tag="debian/${option_release}/${git_tag}"
      echo "Tagging with \"${the_tag}\"."
      git tag "${the_tag}" \
        || { git tag -d "${the_tag}" || echo "no remote tag ${the_tag}." ; for r in $(git remote); do git push "$r" :"${the_tag}" || echo "remote does not have tag ${the_tag}"; done; git tag "${the_tag}"; }
      git push --all || { echo -e "${BRed}ERROR: could not push changes to remote${Color_Off}"; }
      git push --tags || { echo -e "${BRed}ERROR: could not push tags to remote${Color_Off}"; }
    fi
  else
    # This was a snapshot build. Restore the checked in debian/changelog
    # file (the last release).
    echo "Restoring debian/changelog after snapshot build."
    git checkout debian/changelog || echo -e "${BYellow}WARNING: not a git location.${Color_Off}"
  fi

  if [ "$option_do_upload" = true ]; then
    # Upload to the distribution that is in the changelog.
    upload_release=$(dpkg-parsechangelog -S distribution)
    echo "Uploading package ${debian_package} to ${upload_release}, ..."
    dput -u "${upload_release}" "${result_dir}/${debian_package}_${new_noepoch}_${option_architecture}.changes"
  fi
}

function update_debian_changelog {
  echo -e "${BGreen}🤚 Updating debian/changelog, press RETURN to continue...${Color_Off}"
  if [ "${option_update_dch}" = false ]; then
    option_do_commit=false
    option_do_upload=true
    echo -e "${BYellow}WARNING: not updating debian/changelog.${Color_Off}"
  elif [ "$option_silent" = true ]; then
    git_since=$(git log -n1 --format=format:"%H" debian/changelog)

    # Only update the version if it was not passed as an option
    if [ -z "${option_version}" ]; then
      option_version=$(dpkg-parsechangelog --show-field Version | cut -f 1 -d '~' | awk -F. -v OFS=. 'NF==1{print ++$NF}; NF>1{if(length($NF+1)>length($NF))$(NF-1)++; $NF=sprintf("%0*d", length($NF), ($NF+1)%(10^length($NF))); print}')~$(dpkg-parsechangelog --show-field Version | cut -f 2- -d '~' | cut -f 1 -d \+ )+1
    fi
    git log --oneline ${git_since}.. | while read line; do dch "$(echo ${line} | fmt)"; done
    dch --distribution "${builder_release}" --force-distribution "automated update" -v "${option_version}"
  elif [ -n "${option_version}" ]; then
    # A custom version was passed. Use this one
    echo "Using version ${option_version}"
    gbp dch --ignore-branch --distribution "${builder_release}" --release --new-version="${option_version}"
  else
    # Update the changelog of option_do_commit is set, if not; build a
    # snapshot version but do not save or check in the debian/changelog
    if [ "$option_do_commit" = true ]; then
      [ -d .git ] \
        && gbp dch --ignore-branch --force-distribution --distribution "${builder_release}" --release \
        || { git log --pretty=format:'%s' --abbrev-commit $(git log -n 1 --pretty=format:%H -- debian/changelog)^..HEAD . | head -n -1 | while read i; do dch $i; done; dch -r; }
    else
      appendix=$(git describe --tags --match='debian/*' | cut -f 3 -d / | tr - + | cut -f 3- -d +)
      old=${old}"+${appendix}"
      echo "Building package with snapshot version \"${old}\", not saving commit"
      gbp dch --ignore-branch --force-distribution --new-version=${old}
      dch -r --force-distribution --distribution "${builder_release}"
      # ⚠️  a git snapshot build should not be uploaded to the
      # repositories. Set option_do_upload to false
      echo -e "${BYellow}⚠️  This is a snapshot build, disabling upload.${Color_Off}"
      option_do_upload=false
    fi
  fi
  [ "$(type -t test_dch_version)" = 'function' ] && test_dch_version

  new=$(dpkg-parsechangelog --show-field Version)
  echo -e "${BGreen}🤚 new ${debian_package} version: ${new}.${Color_Off}"

  # Conversion of debian package version to a format that git tag
  # can handle
  git_tag=${new//\~/\@}
  git_tag=${git_tag//:/\%}
}

clear_pbuilder_caches() {
  # Simple function to clear the debootstrap cached filesystems

  echo -e "${BYellow}WARNING: clearing pbuilder debootstrap images.${Color_Off}"
  sudo find "${pbuildercache}" -maxdepth 1 -type d  -name 'base-*' -exec rm -rf {} \;
}

function update_local_chroot {
  # Correct the permission of /etc/pbuilderrc
  if [ ! -r "/etc/pbuilderrc" ]; then
    echo "Setting permissions of /etc/pbuilderrc to 644"
    sudo chmod a+r "/etc/pbuilderrc"
  fi

  [ "$(type -t prepare_debootstrap)" = 'function' ] && prepare_debootstrap

  local_chroot=${pbuildercache}/base-${builder_release}-${option_architecture}.cow

  if [ ! -d "${local_chroot}" \
	  -o ! -d "${local_chroot}/etc/" ]; then
    echo "Chroot ${local_chroot} does not exist, creating it, please standby..."
    sudo rm -rf ${local_chroot}

    # Get debian key
    keyfile=$(mktemp)
    wget https://ftp-master.debian.org/keys/release-10.asc -qO- | gpg --import --no-default-keyring --keyring ${keyfile}
    sudo mv "${keyfile}" /etc/apt/trusted.gpg.d/debian-release-10.gpg

    # Just in case that this directory is missing
    sudo mkdir -p /var/cache/pbuilder/aptcache

    # Fail early: when the file is not writable, the sub shell of tee
    # fails; but the entire script. By touching the file that will be used,
    # touch will return an error and let the script exit.
    cowbuilder_log="${result_dir}/cowbuilder_create_${option_architecture}.log"
    touch "${cowbuilder_log}"
    echo -e "${BGreen}🤚 creating pdebuilder chroot with log in ${cowbuilder_log}${Color_Off}"
    sudo cowbuilder --create \
      --basepath ${local_chroot} \
      --distribution ${option_release} \
      --mirror ${option_mirror} \
      --debootstrapopts="--arch=${option_architecture}" \
      --debootstrapopts="--include=${option_additional_packages// /,}" \
      --debootstrapopts="--keyring=${option_keyring}" \
      --hookdir $pbuilder_hook \
      --components "${DISTRO_COMPONENTS}" \
      2>&1 > "${cowbuilder_log}" \
      || { cat "${cowbuilder_log}"; echo "Error while creating chroot, aborting! Log at ${cowbuilder_log}" ; exit 1; }
        echo "${local_chroot} created successfully, log found at ${cowbuilder_log}"
    [ -z "${other_mirror}" ] || { sudo mkdir -p ${local_chroot}/etc/apt/sources.list.d/; sudo bash -c "echo \"${other_mirror}\" | sed -e 's/|/\n/g' > ${local_chroot}/etc/apt/sources.list.d/debian-package-build.list" ; }
    [ -z "${apt_preferences}" ] || { sudo mkdir -p ${local_chroot}/etc/apt/preferences.d/; sudo bash -c "echo \"${apt_preferences}\" | sed -e 's/|/\n/g' > ${local_chroot}/etc/apt/preferences.d/99_televic-preferences" ; }
  fi

  if [ "${option_update_chroot}" = true ]; then
    echo -e "🤚 ${Green}updating chroot ${local_chroot}, please standby...${Color_Off}"
    # Fail early: when the file is not writable, the sub shell of tee
    # fails; but the entire script. By touching the file that will be used,
    # touch will return an error and let the script exit.
    cowbuilder_log="${result_dir}/cowbuilder_update_${option_architecture}.log"
    touch "${cowbuilder_log}"
    echo -e "${BGreen}🤚 updating pdebuilder chroot with log in ${cowbuilder_log}${Color_Off}"
    echo "Adding ${other_mirror} to chroot"
    [ -z "${other_mirror}" ] || { sudo mkdir -p ${local_chroot}/etc/apt/sources.list.d/; sudo bash -c "echo \"${other_mirror}\" | sed -e 's/|/\n/g' > ${local_chroot}/etc/apt/sources.list.d/debian-package-build.list" ; }
    sudo cowbuilder \
      --update \
      --distribution ${option_release} \
      --mirror ${option_mirror} \
      --basepath ${local_chroot} \
      2>&1 > "${cowbuilder_log}" \
      || { cat "${cowbuilder_log}" ; echo "Update failed, aborting! Log at ${cowbuilder_log}" ; exit 1; }
              echo "chroot ${local_chroot} updated, log found at ${cowbuilder_log}"
  fi

  # Always set proper permission of the chroot dir
  sudo chmod 755 ${local_chroot}
}

finish_build() {
  if [ -d .pc ]; then
    echo "Popping applied patches"
    quilt pop -a || { echo -e "${BYellow}Could not pop patches.${Color_Off}"; }
  fi
}

show_packages() {
  if [ -f "${build_log}" ]; then
    echo -e "${BGreen}🤚  List of built packages:${Color_Off}"

    echo -e "${BGreen}"
    grep "building package" "${build_log}" | cut -f 6 -d ' ' | grep -v satisfydepends
    echo -e "${Color_Off}"
  else
    echo -e "${BYellow}⚠️  Could not determine built packages.${Color_Off}"
  fi
}

ARGS=$(getopt -o "a:b:cdhk:m:r:us:Sv:" -l "architecture:,build-branch:,commit,clear-cache,debug,force-upload,help,keyring:,mirror:,no-chroot-update,no-dch,profile:,release:,upload,suite:,version:,skip-tests,source-only,silent" -n "debian-package-build" -- "$@")

eval set -- "$ARGS"

while true; do
  case "$1" in
    -a|--architecture)
      option_architecture=$2
      shift;
      shift;;
    -b|--build-branch)
      option_build_branch=$2
      shift;
      shift;;
    -c|--commit)
      option_do_commit=true
      shift;;
    --clear-cache)
      clear_pbuilder_caches
      exit;;
    -d|-debug)
      option_debug=true
      shift;;
    --force-upload)
      option_force_upload=true
      shift;;
    -h|--help)
      show_help
      exit;;
    -k|--keyring)
      option_additional_packages=$2
      shift;
      shift;;
    -m|--mirror)
      option_mirror=$2
      shift;
      shift;;
    --no-chroot-update)
      option_update_chroot=false
      shift;;
    --no-dch)
      option_update_dch=false
      shift;;
    --profile)
      option_profile=$2
      shift;
      shift;;
    -r|--release)
      option_release=$2
      shift;
      shift;;
    -u|--upload)
      option_do_upload=true
      shift;;
    -v|--version)
      option_version=$2
      shift;
      shift;;
    -s|--suite)
      option_suite=$2
      shift;
      shift;;
    --skip-tests)
      option_skip_tests=true
      shift;;
    --source-only)
      option_source_only=true
      # No need to update the chroot
      option_update_chroot=false
      shift;;
    -S|--silent)
      option_silent=true
      shift;;
    --)
      shift
      break;;
  esac
done

[ "${option_debug}" = false ] || \
  { echo -e "${BYellow}⚠️  enabling debug.${Color_Off}"; set -x; }

# Sanity tests

# am_i_root

is_installed cowbuilder
is_installed cowdancer
is_installed debhelper
is_installed devscripts
is_installed git-buildpackage
is_installed lintian
is_installed meson
is_installed scons
is_installed wget

[ -z "${option_profile}" ] || load_profile

echo "Policy is set to \"${option_profile}\""
echo "Suite is set to \"${option_suite}\""

# if a profile is defined, tests for the extra packages
if [ -n "${option_profile}" ]; then
  # Test the custom profile packages
  for p in ${PROFILE_ADDITIONAL_PACKAGES}; do
    is_installed "${p}"
  done
fi

[ -d debian ] || { echo "⛔ Cannot find debian directory, bailing out."; exit 1; }

trap clean EXIT

# Enforce a number of custom defined profiles.
[ "$(type -t test_policies)" = 'function' ] && test_policies

# FIXME: to investigate how this can be made more generic. For Debian,
# the upload is unstable/testing/stable; for Ubuntu, the upload is the
# release (bionic, focal, ...)
echo "Custom repository is set to \"${option_repository}\""
[ -z "${option_repository}" ] \
  && builder_release=${option_release} \
  || builder_release=${option_release}-${option_repository}-${option_suite}

echo "Build release is set to \"${builder_release}\""

test_debian_changelog
test_dirty_tree

# are we using git?
if [ -d .git ]; then
  clean_git_directory
  update_debian_changelog
  test_existing_git_tag
else
  if [ ${option_update_dch} = "true" ]; then
    dch -n -m "Rebuild on $(hostname)"
    dch -r --force-distribution --distribution ${builder_release}
  fi
  new=$(head -n 1 debian/changelog | cut -f 2 -d \ | tr -d "()")
  echo "New ${debian_package} version: ${new}"
fi

[ "$option_do_commit" = false ] && echo -e "${BGreen}🤚 ${debian_package} version ${new} will not be persisted.${Color_Off}"
[ "$option_do_upload" = false ] && echo -e "${BGreen}🤚 ${debian_package} will not be uploaded.${Color_Off}"

# The building procedure: update the chroot and build within that environment
update_local_chroot
build_package_in_chroot

# Sign the package
debsign ${result_dir}/${debian_package}_${new_noepoch}_${option_architecture}.changes &> /dev/null \
  || { echo -e "${BRed}⛔ There a problem signing the package.${Color_Off}"; exit 1; }

lintian_package_test
upload_package_to_builder
finish_build
show_packages

exit ${return_value}
