#!/usr/bin/env bash

set -euo pipefail

# git build package has moved to sbuild as a backend for isolated debian package
# building using mmdebstrap generated chroots using 'unshare' for non-priveleged
# operation.
#
# the completed chroots can still be managed by th schroot methos/tools.
#
# sbuild caches the chroots it generated in ${HOME}/.cache/sbuild/ and looks
# there for named chroots suitable for build packages eq unstable-amd64.tar

sudo apt-install mmdebstrap

# You can override any of these variables on the command line:
: "${MMDEBSTRAP_HOME:=${HOME}/.config/mmdebstrap}"
: "${CACHE_DIR:=${HOME}/.cache/sbuild}"
: "${ARCH:=amd64}"
: "${VARIANT:=buildd}"
: "${SUITE:=ceres}"
: "${COMPONENT:=main contrib non-free non-free-firmware}"

# Print a nicely‑formatted info line
info() { printf '\033[1;34m%s\033[0m\n' "$*"; }

# Die with an error message
die() {
  printf '\033[1;31mERROR: %s\033[0m\n' "$*" >&2
  exit 1
}

# Ensure a command exists
require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    die "Missing required command: $1"
  fi
}

require_cmd mmdebstrap
require_cmd gpg
require_cmd mkdir
require_cmd cp

# Make a directory for the scripts and hooks used to create mmdebstrap chroots.
mkdir -p ${MMDEBSTRAP_HOME}/{hooks,keyrings}

## Keyrings for apt
# https://files.devuan.org/devuan-archive-keyring.gpg

# Fetch the devuan repo keys
# We don't put this in hooks because we won;t have gpg in the chroot
# early on.
conf_print_download_repo_keys() {
  cat <<EOF
#!/bin/sh

conf_add_keyring() {
  local name="$1"
  local keyid="$2"
  local fingerprint="$3"

  printf '%s\n' "$name ($keyid)"
  printf '%s\n' "Fingerprint: ${fingerprint// /}"

  gpg --keyserver keyring.devuan.org --recv-keys "$keyid"
  gpg --fingerprint "$keyid"

  gpg --export "${fingerprint// /}" >"${MMDEBSTRAP_HOME}/keyrings/devuan-${name,,}.gpg"
  chmod 644 "${MMDEBSTRAP_HOME}/keyrings/devuan-${name,,}.gpg"
}

conf_print_download_repo_keys() {
  conf_add_keyring "Ceres"      "010291FF0AECE9B9" "EFA9 5D75 91EA 95A5 A417 945F 0102 91FF 0AEC E9B9"
  conf_add_keyring "Excalibur"  "B3982868D104092C" "9F8D 6C74 DE66 1075 FD17 1BE3 B398 2868 D104 092C"
  conf_add_keyring "Freia"      "55C470D57732684B" "6A27 69BF 7BE7 9F17 2569 6E0B 55C4 70D5 7732 684B"
  conf_add_keyring "Amprolla3"  "BB23C00C61FC752C" "E032 601B 7CA1 0BC3 EA53 FA81 BB23 C00C 61FC 752C"
  conf_add_keyring "All others" "94532124541922FB" "72E3 CB77 3315 DFA2 E464 743D 9453 2124 5419 22FB"
}

conf_print_download_repo_keys

# copy-in requires the keyrings in /tmp
cp -a "${MMDEBSTRAP_HOME}/keyrings/" /tmp
EOF
}
mkdir -p ${MMDEBSTRAP_HOME}
conf_print_download_repo_keys | tee ${MMDEBSTRAP_HOME}/download-repo-keys.sh
chmod +x ${MMDEBSTRAP_HOME}/download-repo-keys.sh

info "Downloading keys …"
#${MMDEBSTRAP_HOME}/download-repo-keys.sh

# gitea debian package repository keyring for copy-in
cp -a /usr/share/keyrings/gitea-cyteen.gpg /tmp/keyrings/
cp -a /usr/share/keyrings/gitea-cyteen.gpg ${MMDEBSTRAP_HOME}/keyrings/

## hooks
# setup-hook     - before packages are downloaded and installed.
# extract-hook   - after essential packages were extracted but before they are installed.
# essential-hook - after the essential packages were installed, but before installing all other packages.
# customize-hook - after the chroot was created but before finalizing.
# cleanup-hook   - runs after all customize hooks and before final cleanup actions.
# hook-directory - the files in the hook directory must have the prefix of setup, extract, essential, customize, or finalize.
#                  they must be executable and their sequence is determined by their number eg setup01.sh customize01.sh customize02.sh

# Set the Hostname and timezone and add a group
conf_print_setup_tz_locales_hostname() {
  cat <<-'EOF'
#!/bin/sh

set -e

# Set the default debconf frontend to Readline
echo 'debconf debconf/frontend select Readline' | chroot "$1" debconf-set-selections

# Enable the wheel group.
sed -i '15 s/^# //' "$1"/etc/pam.d/su
chroot "$1" addgroup --system wheel

# Set the system's hostname.
echo "sbuildchroot" >"$1"/etc/hostname

# Set the timezone
echo "tzdata tzdata/Areas select Europe"        | chroot "$1" debconf-set-selections
echo "tzdata tzdata/Zones/Europe select London" | chroot "$1" debconf-set-selections
echo 'tzdata tzdata/Zones/Etc select UTC'       | chroot "$1" debconf-set-selections

# This has to be done or else dpkg-reconfigure insists on using Etc
# as the default timezone for whatever stupid reason.
echo "Europe/London" >"$1"/etc/timezone
chroot "$1" ln -sf "/usr/share/zoneinfo/Europe/London" /etc/localtime
chroot "$1" dpkg-reconfigure -f noninteractive tzdata

# Set locale
echo "locales locales/default_environment_locale select en_GB.UTF-8"         | chroot "$1" debconf-set-selections
echo "locales locales/locales_to_be_generated multiselect en_GB.UTF-8 UTF-8" | chroot "$1" debconf-set-selections
chroot "$1" apt-get install locales -y
EOF
}
mkdir -p ${MMDEBSTRAP_HOME}/hooks
conf_print_setup_tz_locales_hostname | tee ${MMDEBSTRAP_HOME}/hooks/customize01.sh
chmod +x ${MMDEBSTRAP_HOME}/hooks/customize01.sh

# apt sources
conf_print_ceres_sources() {
  cat <<-'FOE'
Types: deb
URIs: https://git2.ring-zero.co.uk/api/packages/cyteen/debian/
Suites: ceres
Components: main 
Signed-By: /usr/share/keyrings/gitea-cyteen.gpg
FOE
}
mkdir -p ${MMDEBSTRAP_HOME}
conf_print_ceres_sources | tee ${MMDEBSTRAP_HOME}/gitea-cyteen.sources

conf_print_ceres_sources() {
  cat <<-'FOE'
Types: deb
URIs: https://pkgmaster.devuan.org/merged/
Suites: ceres
Components: main  contrib non-free non-free-firmware
Signed-By: /usr/share/keyrings/devuan-ceres.gpg

Types: deb-src
URIs: https://pkgmaster.devuan.org/merged/
Suites: ceres
Components: main contrib non-free non-free-firmware
Signed-By: /usr/share/keyrings/devuan-ceres.gpg
FOE
}
mkdir -p ${MMDEBSTRAP_HOME}
conf_print_ceres_sources | tee ${MMDEBSTRAP_HOME}/devuan_ceres.sources

# When using sbuild and wanting a gitea as an extra repo add this to
# ${HOME}/.config/sbuild/config.pl works
# $extra_repositories = [ 'deb https://git2.ring-zero.co.uk/api/packages/cyteen/debian ceres main' ];
# $extra_repository_keys = [ '/usr/share/keyrings/gitea-cyteen.gpg' ];

# Copy the sources created above into the chroot

conf_print_copy_in_ceres_sources() {
  cat <<EOF
#!/bin/sh
set -e
mkdir -p \"$1\"/usr/share/keyrings
#mkdir -p \"$1\"/etc/apt/trusted.gpg.d
cp "${MMDEBSTRAP_HOME}/keyrings/devuan-ceres.gpg" \"$1\"/usr/share/keyrings/
cp "${MMDEBSTRAP_HOME}/keyrings/gitea-cyteen.gpg" \"$1\"/usr/share/keyrings/
cp "${MMDEBSTRAP_HOME}/devuan_ceres.sources" "\$1\"/etc/apt/sources.list.d/
cp "${MMDEBSTRAP_HOME}/gitea-cyteen.sources" "\$1\"/etc/apt/sources.list.d/
ls "$1"/usr/share/keyrings/
EOF

}
mkdir -p ${MMDEBSTRAP_HOME}/hooks
#conf_print_copy_in_ceres_sources | tee ${MMDEBSTRAP_HOME}/hooks/setup01.sh
#chmod +x ${MMDEBSTRAP_HOME}/hooks/setup01.sh

info "Creating Devuan $SUITE chroot …"

# Use a temporary directory for mmdebstrap’s cache if TMPDIR is unset
: "${TMPDIR:=/var/tmp}"
export TMPDIR

# Use a temporary directory for mmdebstrap’s cache if TMPDIR is unset
: "${TMPDIR:=/var/tmp}"
export TMPDIR

# The final tarball location
OUT_TAR="${CACHE_DIR}/unstable-${ARCH}.tar"

# Although the signed-by from the sources is used for the build of the chroot
# if you want the chroot to have working keys for apt you have to copy-in to
# the usual location. They say it can copy any file accessable to the user but
# copying from /tmp/works if copying from $HOME doesn't.
#  --setup-hook='copy-in ${MMDEBSTRAP_HOME}/keyrings/devuan-ceres.gpg /usr/share/keyrings/' \
#  --setup-hook='copy-in /usr/share/keyrings/gitea-ceres.gpg /usr/share/keyrings/' \
#  --setup-hook='copy-in /etc/apt/sources.list.d/gitea-private.sources /etc/apt/sources.list.d/' \

#  --setup-hook='copy-in /tmp/keyrings/devuan-ceres.gpg /usr/share/keyrings/' \
#  --setup-hook='copy-in /tmp/keyrings/gitea-ceres.gpg /usr/share/keyrings/' \
#  --setup-hook='copy-in /etc/apt/sources.list.d/gitea-private.sources /etc/apt/sources.list.d/' \

mmdebstrap \
  --mode="unshare" \
  --variant=${VARIANT} \
  --arch=${ARCH} \
  --Components="main contrib non-free non-free-firmware" \
  --skip=output/mknod \
  --format=tar \
  --include=sudo,curl,adduser,tzdata,git,gpg,ca-certificates \
  --setup-hook='mkdir -p "$1"/usr/share/keyrings/' \
  --setup-hook='mkdir -p "$1"/etc/apt/sources.list.d/' \
  --setup-hook='copy-in ${MMDEBSTRAP_HOME}/keyrings/devuan-ceres.gpg /usr/share/keyrings/' \
  --setup-hook='copy-in /usr/share/keyrings/gitea-ceres.gpg /usr/share/keyrings/' \
  --setup-hook='copy-in /etc/apt/sources.list.d/gitea-private.sources /etc/apt/sources.list.d/' \
  --setup-hook='ls -lh "$1"/usr/share/keyrings/' \
  --hook-directory=hooks \
  --include=ccache \
  --customize-hook='chroot "$1" update-ccache-symlinks' \
  --include=eatmydata \
  unstable "${OUT_TAR}" \
  ${MMDEBSTRAP_HOME}/devuan_${SUITE}.sources

unset TMPDIR
