#!/usr/bin/env bash

# Add a sources.list that points to the gitea instance.
# https://docs.gitea.com/usage/packages/debian

GITEA_URL="git2.ring-zero.co.uk"
OWNER="cyteen"
DISTRIBUTION="ceres"
COMPONENT="main"
KEYRING="/etc/apt/trusted.gpg.d/gitea-${OWNER}.gpg"

# system wide keyrings conflict with trusted.gpg
if [ -f /etc/apt/keyrings/gitea-cyteen.asc ]; then
	rm /etc/apt/keyrings/gitea-cyteen.asc
fi

# the existance of the apt_auth is the only difference.
# cat <<-EOF | sudo tee /etc/apt/sources.list.d/gitea.list
# 	deb [signed-by=${KEYRING}] https://${GITEA_URL}/api/packages/${OWNER}/debian ${DISTRIBUTION} ${COMPONENT}
# EOF

USERNAME="cyteen"
PASSWORD="mlpfinsonik"
cat <<-EOF | sudo tee /etc/apt/sources.list.d/gitea-private.list
	deb [signed-by=${KEYRING}] https://${GITEA_URL}/api/packages/${OWNER}/debian ${DISTRIBUTION} ${COMPONENT}
EOF

# fetch the gitea signed-by key
curl -fsSL https://${GITEA_URL}/api/packages/${OWNER}/debian/repository.key | gpg --dearmor -q | sudo tee ${KEYRING} >/dev/null

# rather than put username:password@ in the url to gitea we use apt_auth
conf_print_apt_auth() {
	cat <<-EOF
		machine ${GITEA_URL}
		login ${USERNAME}
		password ${PASSWORD}
	EOF
}

if [ ! -f /etc/apt/auth.conf.d/${GITEA_URL} ]; then
	conf_print_apt_auth | sudo tee /etc/apt/auth.conf.d/${GITEA_URL} >/dev/null
fi

sudo apt-get update

# # Publish a package
# ARCHIVE="/var/cache/apt/archives/"
# PACKAGE="rustc_1.70.0+dfsg1-7_amd64.deb"
# curl --user your_username:your_password_or_token \
# 	--upload-file ${ARCHIVE}/${PACKAGE} \
# 	https://${GITEA_URL}/api/packages/${OWNER}/debian/pool/${DISTRIBUTION}/${COMPONENT}/upload
#
# # Delete a package
# curl --user ${USERNAME}:${PASSWORD} -X DELETE \
# 	https://${GITEA_URL}/api/packages/${OWNER}/debian/pools/${DISTRIBUTION}/main/test-package/1.0.0/amd64
