#!/bin/bash

# Copyright (C) 2025  Association foOpgp <info@foopgp.org>
# Author: Sébastien Picardeau (u4D9SrwuxesuMU90PM8xypxQe_48.78_002.19) <piseb@foopgp.org>
#
# 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, version 3.
#
# 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 <https://www.gnu.org/licenses/>.

set -euo pipefail

# A public apt archive must be readable by apache and the world; keep the
# indexes group/world readable (and not group-writable) whatever the caller's
# umask, matching djibian-debs-build.
umask 022

# Regenerate the apt indexes (Packages, per-arch Contents, Release, InRelease)
# of an archive directory. Pass the directory, or run inside it.
# Usage: djibian-debs-index [ARCHIVE_DIR]
case "${1:-}" in
  -h|--help) echo "Usage: djibian-debs-index [ARCHIVE_DIR]" ; exit 0 ;;
esac
cd "${1:-.}"
dpkg-scanpackages -m . > Packages
gzip -k -f Packages
# One Contents index per architecture present -- see archives/build.sh for
# why a single Contents-amd64 is wrong as soon as the archive is not amd64
# only. sed rather than grep: grep returns 1 when it filters everything out,
# and this script runs under set -e.
for arch in $(find . -maxdepth 1 -name '*.deb' -exec dpkg-deb --field {} Architecture \; \
              | sort --unique | sed '/^all$/d') ; do
  rm -rf ".contents-$arch" ; mkdir ".contents-$arch"
  find . -maxdepth 1 \( -name "*_$arch.deb" -o -name '*_all.deb' \) \
       -exec ln -sf "$PWD/{}" ".contents-$arch/" \;
  apt-ftparchive contents ".contents-$arch" > "Contents-$arch"
  gzip -k -f "Contents-$arch"
  rm -rf ".contents-$arch"
done
apt-ftparchive release . > Release

gpg --clearsign -o - Release > InRelease
