#!/bin/bash
set -euo pipefail
shopt -s nullglob

archs=(amd64 armel armhf i386 arm64)

export TMPDIR=/var/tmp

if [[ ! -z ${1:-} ]] ; then
	workdir=$(mktemp -d)
	echo Working dir is "$workdir"
	pushd "$workdir" >/dev/null

	echo Downloading release
	cp "$1"/*.deb .

	ver=(syncthing_*_amd64.deb)
	ver="${ver#syncthing_}"
	ver="${ver%_amd64.deb}"

	for arch in "${archs[@]}" ; do
		mv "syncthing_${ver}_${arch}.deb" "$HOME/apt-dists/pool"
	done

	popd >/dev/null
	rm -r "$workdir"
fi

pushd "$HOME/apt-dists" >/dev/null

echo Cleaning out old releases
find "pool" -name syncthing_\*.deb -mtime +60 -delete

echo Generating and signing package archives
shopt -s nullglob

for arch in "${archs[@]}" ; do
	for chan in release stable ; do
		path="dists/syncthing/$chan/binary-$arch"
		pushd "$path"
		rm -f *
		ln -s ../../../../pool/*_{[0-9],[0-9][0-9]}.{[0-9],[0-9][0-9]}.{[0-9],[0-9][0-9]}_$arch.deb . || true
		popd
		dpkg-scanpackages -m "$path" > "$path/Packages"
		gzip -c "$path/Packages" > "$path/Packages.gz"
	done

	path="dists/syncthing/candidate/binary-$arch"
	pushd "$path"
	rm -f *
	ln -s ../../../../pool/*_$arch.deb . || true
	popd
	dpkg-scanpackages -m "$path" > "$path/Packages"
	gzip -c "$path/Packages" > "$path/Packages.gz"
done

apt-ftparchive -c Releases.conf release dists/syncthing | gpg --clearsign > dists/syncthing/InRelease
gzip -c dists/syncthing/InRelease > dists/syncthing/InRelease.gz
apt-ftparchive -c Releases.conf release dists/syncthing > dists/syncthing/Release
gzip -c dists/syncthing/Release > dists/syncthing/Release.gz
gpg --detach-sign --yes -a -o dists/syncthing/Release.gpg dists/syncthing/Release
gzip -c dists/syncthing/Release.gpg > dists/syncthing/Release.gpg.gz

echo Uploading new distribution
rsync -va --delete --rsh="$RSYNC_RSH_CMD" ./ "$RELEASE_ROOT/"

