#!/usr/bin/env bash
#
# GitHub Actions Scripts
# Copyright (C) 2021-2023 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 -e

UNAME=`uname`
USE_PACKAGING=0

while [ $# -gt 0 ] ; do
   if [ "$1" == "package" ] ; then
      USE_PACKAGING=1
   fi
   shift
done


# ###### Linux ##############################################################
if [ "${UNAME}" == "Linux" ] ; then

   # NOTE: lsb_release may not be installed, yet!
   # => Guess distribution by checking for the packaging tool.

   # ====== Ubuntu/Deban ====================================================
   if [ -e /usr/bin/apt-get ] ; then
      PACKAGES="lsb-release python3"
      if [[ "${CC}" =~ .*gcc.* ]] ; then
          PACKAGES="${PACKAGES} gcc"
      elif [[ "${CC}" =~ .*clang.* ]] ; then
          PACKAGES="${PACKAGES} clang"
      fi
      if [ ${USE_PACKAGING} -eq 1 ] ; then
         # Need to install pbuilder as well:
         PACKAGES="${PACKAGES} build-essential debian-archive-keyring debian-ports-archive-keyring devscripts eatmydata fakeroot lintian pbuilder python3-debian qemu-user-static"
      fi

      apt-get update -qq
      # DEBIAN_FRONTEND=noninteractive apt-get dist-upgrade -qy
      DEBIAN_FRONTEND=noninteractive apt-get install -qqy  -o Dpkg::Options::=--force-confold -o Dpkg::Options::=--force-confdef --no-install-recommends \
         ${PACKAGES}

      if [ "`lsb_release -is`" == "Ubuntu" ] ; then
         # Add PPA dreibh/ppa for Ubuntu:
         DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::=--force-confold -o Dpkg::Options::=--force-confdef --no-install-recommends \
            software-properties-common
         apt-add-repository -y ppa:dreibh/ppa || true
         apt-get update -q
      fi

      if [ ${USE_PACKAGING} -eq 1 ] ; then
         # ====== pbuilder environment ======================================
         # Example for GitHub Actions:
         # https://github.com/jrl-umi3218/github-actions/tree/master/setup-pbuilder

         if [ "${OS}" == "" ] ; then
            OS=`lsb_release -is`
            OS=${OS,,}
         fi
         if [ "${DIST}" == "" ] ; then
            DIST=`lsb_release -cs`
         fi
         if [ "${ARCH}" == "" ] ; then
            ARCH=`dpkg --print-architecture`
         fi

         if [ "${OS}" == "ubuntu" ] ; then
            COMPONENTS="main universe"
            MIRRORSITE=http://no.archive.ubuntu.com/ubuntu/
            KEYRING="/usr/share/keyrings/ubuntu-archive-keyring.gpg"
         elif [ "${OS}" == "debian" ] ; then
            COMPONENTS="main"
            if [ "${ARCH}" == "m68k" -o  "${ARCH}" == "riscv64" ] ; then
               # Debian Ports (special architectures)
               MIRRORSITE="http://ftp.ports.debian.org/debian-ports/"
               KEYRING="/usr/share/keyrings/debian-ports-archive-keyring.gpg"
            else
               # Debian (supported architectures)
               MIRRORSITE="http://ftp.no.debian.org/debian/"
               KEYRING="/usr/share/keyrings/debian-archive-keyring.gpg"
            fi
         else
            echo >&2 "ERROR: Unknown Linux distribution ${OS}!"
            exit 1
         fi

         cores=`getconf _NPROCESSORS_ONLN 2>/dev/null || true`
         cat >/etc/pbuilderrc <<EOF
#!/bin/bash -e

# ====== Settings ===========================================================
DISTRIBUTION="${DIST}"
COMPONENTS="${COMPONENTS}"
MIRRORSITE="${MIRRORSITE}"
DEBOOTSTRAPOPTS=("\${DEBOOTSTRAPOPTS[@]}" "--keyring=${KEYRING}")
DEBOOTSTRAPOPTS=("\${DEBOOTSTRAPOPTS[@]}" "--variant=buildd")
ARCHITECTURE="${ARCH}"

APTCACHEHARDLINK=no

USECOLORS=yes
COMPRESSPROG=cat
EXTRAPACKAGES=eatmydata
EATMYDATA=yes

# Multi-core: set concurrency level. The packaging scripts will handle it properly:
export CONCURRENCY_LEVEL=${cores}
export DEB_BUILD_OPTIONS="parallel=${cores}"

# ====== Directories ========================================================
NAME="\${OS}-\${DISTRIBUTION}-\${ARCHITECTURE}"
BASETGZ="/var/cache/pbuilder/\${NAME}-base.tgz"
APTCACHE="/var/cache/pbuilder/aptcache/\${NAME}/"
BUILDPLACE="/var/cache/pbuilder/build/\${NAME}/"
BUILDRESULT="/var/cache/pbuilder/result/\${NAME}/"
HOOKDIR="/var/cache/pbuilder/hook.d/"

mkdir -p \${APTCACHE}
mkdir -p \${BUILDRESULT}
mkdir -p \${HOOKDIR}
EOF
         echo "----- /etc/pbuilderrc: ------------------------------------------------------"
         cat /etc/pbuilderrc
         echo "-----------------------------------------------------------------------------"

         pbuilder create \
            --debootstrapopts --variant=buildd \
            | grep -v "^I: Retrieving\|^I: Validating\|^I: Unpacking\|^I: Extracting\|^I: Configuring\|^I: new cache content"
            # --debootstrapopts --keyring=/etc/apt/trusted.gpg

         # Speed up pbuilder:
         echo "echo \"force-unsafe-io\" > /etc/dpkg/dpkg.cfg.d/02apt-speedup" | \
            pbuilder login --save-after-exec

         # ====== Add ppa:dreibh/ppa, updates and backports =================
         if [ "${OS}" == "ubuntu" ] ; then
            # Add PPA dreibh/ppa for Ubuntu:
            pbuilder login --save-after-login <<EOF
DEBIAN_FRONTEND=noninteractive apt-get install -qqy -o Dpkg::Options::=--force-confold -o Dpkg::Options::=--force-confdef --no-install-recommends \
   software-properties-common
apt-add-repository -y ppa:dreibh/ppa
apt-get update -q
EOF
         fi

      fi


   # ====== Fedora ==========================================================
   elif [ -e /usr/bin/dnf ] ; then
      PACKAGES="clang make python3 redhat-lsb-core"
      if [ ${USE_PACKAGING} -eq 1 ] ; then
         # Need to install mock as well:
         PACKAGES="${PACKAGES} fedora-release findutils mock nosync rpmdevtools"
      fi

      # dnf upgrade -qy
      dnf install -qy ${PACKAGES}

      if [ ${USE_PACKAGING} -eq 1 ] ; then
         # ====== mock environment ==========================================
         groupadd -f mock

         release=`cat /etc/fedora-release | sed -e "s/^\(.*\) release \([0-9]*\) (\(.*\))$/\2/g" | sed -e  "s/[^0-9]//g"`
         arch=`uname -m | sed -e "s/[^0-9a-zA-Z_+-]//g"`
         if ! grep "^\[copr-dreibh-ppa\]" /etc/mock/fedora-${release}-${arch}.cfg ; then
            shopt -s extglob
            ppa="config_opts['dnf.conf'] += \"\"\"\n[copr-dreibh-ppa]\nname=Copr repo for ppa owned by dreibh\nbaseurl=https://copr-be.cloud.fedoraproject.org/results/dreibh/ppa/fedora-\$releasever-\$basearch/\ntype=rpm-md\nskip_if_unavailable=True\ngpgcheck=1\ngpgkey=https://copr-be.cloud.fedoraproject.org/results/dreibh/ppa/pubkey.gpg\nrepo_gpgcheck=0\nenabled=1\n\"\"\""
            ppa="${ppa//+( )$/\\n}"
            echo -e "${ppa}" | tee -a /etc/mock/fedora-${release}-${arch}.cfg
            if ! grep "^\[copr-dreibh-ppa\]" /etc/mock/fedora-${release}-${arch}.cfg ; then
               echo >&2 "ERROR: Unable to inject PPA configuration into Mock configuration file /etc/mock/fedora-${release}-${arch}.cfg!"
               exit 1
            fi
         fi
      fi


   # ====== Unknown =========================================================
   else
      echo >&2 "ERROR: Unknown Linux distribution!"
      exit 1
   fi

# ###### FreeBSD ############################################################
elif [ "${UNAME}" == "FreeBSD" ] ; then

   ASSUME_ALWAYS_YES=yes pkg install -y bash gcc libtool git python3

   # Ports collection:
   # This is the slow method via portsnap:
   # portsnap --interactive fetch extract | grep -v ^/usr/ports
   # Using Git is much faster:
   rm -rf /usr/ports
   git clone --depth=1 https://github.com/freebsd/freebsd-ports /usr/ports

# ###### Unknown ############################################################
else

   echo >&2 "ERROR: Unexpected system ${UNAME}!"
   exit 1

fi
