#!/bin/sh
# This script publishes Debian packages. When run by `mk`, it's
# run inside of an `ubuntu:20.04` container. It's fine also to run
# this script from a live Debian-like system as long as all the
# following assumptions are met:
#
# 1. Debian packages we want to publish are in the toplevel dir.

# ensure that we have all the required environment variables.
fail=0
if [ -z "$AWS_ACCESS_KEY_ID" ]; then
	echo "warning: missing AWS_ACCESS_KEY_ID environment variable" 1>&2
	fail=1
fi
if [ -z "$AWS_SECRET_ACCESS_KEY" ]; then
	echo "warning: missing AWS_SECRET_ACCESS_KEY environment variable" 1>&2
	fail=1
fi
if [ -z "$DEB_GPG_KEY" ]; then
	echo "warning: missing DEB_GPG_KEY environment variable" 1>&2
	fail=1
fi
if [ $fail -ne 0 ]; then
	exit 1
fi

set -ex

export DEBIAN_FRONTEND=noninteractive

maybe_with_sudo() {
	if command -v sudo 1>/dev/null; then
		sudo "$@"
	else
		"$@"
	fi
}

# install the dependencies required by the uploader.
maybe_with_sudo apt-get update -q
maybe_with_sudo apt-get install --yes --no-install-recommends curl git make python3 python3-requests python3-gnupg s3cmd

# pull the latest version of the debops-ci script from ooni/sysadmin.
curl -fsSLO https://raw.githubusercontent.com/ooni/sysadmin/master/tools/debops-ci
chmod +x debops-ci

# loop over the available packages and upload.
for debpkg in *.deb; do
	# for example: ooniprobe-cli_3.10.0_i386.deb
	arch=$(echo "$debpkg" | awk -F_ '{print $3}' | sed 's/\.deb$//g')
	./debops-ci --show-commands upload --bucket-name ooni-deb --arch "$arch" "$debpkg"
done
