#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
set -euo pipefail
uid=${1:?}
gid=${2:?}
apt_cache=${3:-enabled}
[[ $apt_cache == enabled || $apt_cache == disabled ]]
export DEBIAN_FRONTEND=noninteractive
install -m 644 /work/input/debian.sources /etc/apt/sources.list.d/plasma-next.sources
printf '# See sources.list.d/plasma-next.sources\n' > /etc/apt/sources.list
printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d
chmod 755 /usr/sbin/policy-rc.d
apt-get update
python3 - <<'PYCODE'
import hashlib,json
from pathlib import Path
for entry in json.loads(Path('/work/input/snapshot-indexes.json').read_text()):
 paths=list(Path('/var/lib/apt/lists').glob('*_dists_'+entry['suite']+'_InRelease'))
 assert len(paths)==1 and hashlib.sha256(paths[0].read_bytes()).hexdigest()==entry['sha256'],entry['suite']
PYCODE
cache_packages=()
if [[ $apt_cache == enabled ]]; then
    cache_packages+=(apt-cacher-ng)
fi
apt-get --yes --no-install-recommends install "${cache_packages[@]}" sbuild mmdebstrap uidmap iproute2 sudo debhelper dpkg-dev fakeroot lintian reprepro apt-utils gnupg ca-certificates debian-archive-keyring python3
getent group builder >/dev/null || groupadd --gid "$gid" builder
id builder >/dev/null 2>&1 || useradd --uid "$uid" --gid "$gid" --create-home --shell /bin/bash builder
[[ $(id -u builder) == "$uid" && $(id -g builder) == "$gid" ]]
usermod --lock builder
printf 'builder:100000:65536\n' > /etc/subuid
printf 'builder:100000:65536\n' > /etc/subgid
install -d -o builder -g builder /work/{tmp,chroots,results,sources,repository,records,state}
if [[ $apt_cache == enabled ]]; then
    install -d -o builder -g builder /work/apt-cache
fi
install -m 644 /work/input/sbuild.conf /etc/sbuild/sbuild.conf
if [[ ! -f /work/chroots/trixie-amd64.tar ]]; then
 mmdebstrap --mode=root --format=tar --variant=buildd --architectures=amd64 --include=ca-certificates,debian-archive-keyring --skip=output/dev trixie /work/chroots/trixie-amd64.tar.tmp /work/input/debian.sources
 mv /work/chroots/trixie-amd64.tar.tmp /work/chroots/trixie-amd64.tar
 sha256sum /work/chroots/trixie-amd64.tar > /work/records/build-root.sha256
fi
sha256sum --check /work/records/build-root.sha256
mkdir -p /work/repository/conf
cat > /work/repository/conf/distributions <<'CONF'
Origin: Plasma Next
Label: Plasma Next build dependencies
Codename: plasma-next
Suite: plasma-next
Architectures: amd64 source
Components: main
Description: Workspace-local build dependency repository
CONF
reprepro --basedir /work/repository export plasma-next
chown -R builder:builder /work/repository
chown builder:builder /work/chroots/trixie-amd64.tar /work/records/build-root.sha256
printf '%s\n' "$apt_cache" > /etc/plasma-next-apt-cache
