#!/usr/bin/env bash
# ==========================================================================
#              ____        _ _     _     _____           _
#             | __ ) _   _(_) | __| |   |_   _|__   ___ | |___
#             |  _ \| | | | | |/ _` |_____| |/ _ \ / _ \| / __|
#             | |_) | |_| | | | (_| |_____| | (_) | (_) | \__ \
#             |____/ \__,_|_|_|\__,_|     |_|\___/ \___/|_|___/
#
#                           --- Build-Tools ---
#                https://www.nntb.no/~dreibh/system-tools/
# ==========================================================================
#
# Packaging Scripts
# Copyright (C) 2012-2026 by Thomas Dreibholz
#
# 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 3 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com

# Bash options:
set -eu


create-pbuilder ()
{
   local os="$1"
   local dist="$2"
   local arch="$3"
   local name="${os}-${dist}-${arch}"
   local logfile="${name}.log"

   if [ ! -e "/var/cache/pbuilder/${name}-base.tgz" ] ; then
      startTime=$(date +%FT%H:%M:%S)
      echo "${startTime}: Starting to build ${name}, logfile is ${logfile} ..."

      # ====== pbuilder =====================================================
      (
         (
            echo "OS=${os} DIST=${dist} ARCH=${arch}"
            sudo OS="${os}" DIST="${dist}" ARCH="${arch}" pbuilder create | \
               ( grep -v "^I: Retrieving\|^I: Validating\|^I: Unpacking\|^I: Extracting\|^I: Configuring\|^I: new cache content" || true )

               sudo OS="${os}" DIST="${dist}" ARCH="${arch}" pbuilder login --save-after-login <<EOF
# No need for sync:
echo "force-unsafe-io" >/etc/dpkg/dpkg.cfg.d/force-unsafe-io
# Enable official updates repository:
(
   if [ "${os}" == "ubuntu" ] ; then
      echo "deb http://dk.archive.ubuntu.com/ubuntu/ ${dist}-updates main universe restricted "
      echo "# deb-src http://dk.archive.ubuntu.com/ubuntu/ ${dist}-updates main universe restricted"
   elif [ "${os}" == "debian" ] ; then
      if [ "${dist}" != "unstable" ] ; then
         echo "deb http://security.debian.org/debian-security ${dist}-security main non-free-firmware"
         echo "# deb-src http://security.debian.org/debian-security ${dist}-security main non-free-firmware"
      fi
   fi
) >>/etc/apt/sources.list
# Add PPA for Ubuntu:
if [ "${os}" == "ubuntu" ] ; then
   apt-get install -qy software-properties-common
   apt-add-repository -y ppa:dreibh/ppa
   apt-get update -q
fi
apt-get dist-upgrade -y
# Install common build tools:
apt-get install -qy build-essential debhelper cmake
EOF
         ) >"${logfile}" 2>&1

         finishTime=$(date +%FT%H:%M:%S)
         echo "${finishTime}: Finished to build ${name}, logfile is ${logfile}"
         grep ERROR "${logfile}"
      ) &

   else
      echo "${name} (/var/cache/pbuilder/${name}-base.tgz) is already there -> running UPDATE only!"
      (
         (
            echo "OS=${os} DIST=${dist} ARCH=${arch}"
            sudo OS="${os}" DIST="${dist}" ARCH="${arch}" pbuilder update
         ) >"${logfile}" 2>&1

         finishTime=$(date +%FT%H:%M:%S)
         echo "${finishTime}: Finished to build ${name}, logfile is ${logfile}"
         grep ERROR "${logfile}"
      ) &
   fi
}


# ====== Some checks ========================================================
if [ ! -x /usr/bin/qemu-m68k-static ] ; then
   echo >&2 "ERROR: qemu-user-static is not installed!"
   echo >&2 "To fix: sudo apt install -y qemu-user-static"
fi
if [ ! -e /usr/share/keyrings/debian-ports-archive-keyring.gpg ] ; then
   echo >&2 "ERROR: Missing keyring /usr/share/keyrings/debian-archive-keyring!"
   echo >&2 "To fix: sudo apt install -y debian-archive-keyring"
fi
if [ ! -e /usr/share/keyrings/debian-ports-archive-keyring.gpg ] ; then
   echo >&2 "ERROR: Missing keyring /usr/share/keyrings/debian-ports-archive-keyring!"
   echo >&2 "To fix: sudo apt install -y debian-ports-archive-keyring"
fi


# !!!!!! TEST ONLY !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# create-pbuilder ubuntu resolute amd64
# create-pbuilder debian unstable amd64
# wait
# exit 1
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


# ====== Ubuntu =============================================================
ubuntuDistributions="$( (
   ubuntu-distro-info --stable
   ubuntu-distro-info --supported
   ubuntu-distro-info --supported-esm
   ubuntu-distro-info --devel 2>/dev/null || echo "resolute"
) | sort -u)"

for distribution in ${ubuntuDistributions} ; do
   for architecture in amd64 arm64 armhf riscv64 s390x ; do
      create-pbuilder ubuntu "${distribution}" "${architecture}"
   done
done

# ====== Debian =============================================================
debianDistributions="$( (
   debian-distro-info --stable
   debian-distro-info --oldstable
   debian-distro-info --testing
   echo "unstable"
) | sort -u)"

for distribution in ${debianDistributions} ; do
   # for architecture in amd64 arm64 armhf ; do
   for architecture in amd64 arm64 ; do
      create-pbuilder debian "${distribution}" "${architecture}"
   done
done

# for distribution in unstable ; do
# #    for architecture in amd64 arm64 armhf i386 m68k riscv64 ppc64el s390x mipsel ; do
#    for architecture in amd64 arm64 ; do
#       create-pbuilder debian "${distribution}" "${architecture}"
#    done
# done

wait
