#!/usr/bin/env bash

set -e
set -u

buildPackage() {
  DIR="$(basename "$(pwd)")"
  tar c -C ../ --exclude="${DIR}/${DIR}" --exclude="${DIR}/.git" "${DIR}" | tar x
  (
    cd "${DIR}"
    DEB_BUILD_OPTIONS='nocheck' DEB_BUILD_PROFILES='nocheck' dpkg-buildpackage -G --no-sign
  )
  test "$(find -maxdepth 1 -\( -name '*.dsc' -or -name '*.deb' -\) | wc -l)" == "3"
}

(. /etc/os-release; sed -i "s/unstable/${VERSION_CODENAME}/" "${CI_PROJECT_DIR}/debian/changelog")
sed -i "s/(${VERSION})/(${VERSION}+${SUFFIX})/" "${CI_PROJECT_DIR}/debian/changelog"
apt update -qq
apt install -y --no-install-recommends ca-certificates curl ccache
(. /etc/os-release; echo 'deb https://packages.megami.fr/debian/ '${VERSION_CODENAME}' main' > /etc/apt/sources.list.d/megami.list)
curl -sSL https://packages.megami.fr/pubkey.asc > /etc/apt/trusted.gpg.d/megami.asc
apt update -qq
yes | (cd /tmp; DEBIAN_FRONTEND=noninteractive mk-build-deps --install "${CI_PROJECT_DIR}/debian/control")

export CCACHE_DIR="${CCACHE_DIR:-${CI_PROJECT_DIR}/.ccache}"
export CCACHE_BASEDIR="${CCACHE_BASEDIR:-${CI_PROJECT_DIR}}"
export CCACHE_COMPILERCHECK="${CCACHE_COMPILERCHECK:-content}"
export PATH="/usr/lib/ccache:${PATH}"
ccache -z

buildPackage

ccache -s
